Bạn có thể sử dụng $ hoặc toán tử cùng với giới hạn (1) để so khớp phần tử trong mảng. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.matchElementInArrayDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
},
{
"StudentCountryName" : "UK",
"StudentSkills" : "Java"
}
]
}
{
"_id" : ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "AUS",
"StudentSkills" : "PHP"
},
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
}
]
} Đây là truy vấn để so khớp phần tử trong mảng MongoDB -
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }