Để lấy các mục mảng trong tài liệu MongoDB, hãy sử dụng ký hiệu dấu chấm (.). Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo29.insertOne({"StudentDetails":[{"StudentName":"Chris","StudentMarks":58},{"StudentName":"Bob","StudentMarks":69}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e15fcc08f2315c2efc48e6e")
}
>db.demo29.insertOne({"StudentDetails":[{"StudentName":"David","StudentMarks":97},{"StudentName":"Carol","StudentMarks":96}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e15fcd38f2315c2efc48e6f")
} 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.demo29.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e15fcc08f2315c2efc48e6e"),
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentMarks" : 58
},
{
"StudentName" : "Bob",
"StudentMarks" : 69
}
]
}
{
"_id" : ObjectId("5e15fcd38f2315c2efc48e6f"),
"StudentDetails" : [
{
"StudentName" : "David",
"StudentMarks" : 97
},
{
"StudentName" : "Carol",
"StudentMarks" : 96
}
]
} Sau đây là truy vấn để lấy các mục mảng bên trong tài liệu MongoDB -
> db.demo29.find({"StudentDetails.StudentName":"David"}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e15fcd38f2315c2efc48e6f"), "StudentDetails" : [ { "StudentName" : "David", "StudentMarks" : 97 }, { "StudentName" : "Carol", "StudentMarks" : 96 } ] }