Đối với điều này, bạn có thể sử dụng $ và cùng với ký hiệu dấu chấm (.). 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.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
} 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.demo2.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e08b56e25ddae1f53b62219"),
"StudentInformation" : [
{
"StudentName" : "John",
"StudentAge" : 21
},
{
"StudentName" : "Mike",
"StudentAge" : 22
}
]
}
{
"_id" : ObjectId("5e08b58625ddae1f53b6221a"),
"StudentInformation" : [
{
"StudentName" : "Carol",
"StudentAge" : 19
},
{
"StudentName" : "Bob",
"StudentAge" : 18
}
]
} Sau đây là truy vấn để lấy tài liệu có chứa các thuộc tính cụ thể trong mảng−
>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }