Đối với điều này, hãy sử dụng dấu gạch dưới kép (__) trong find (). 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.nestedDemo.insertOne({"Information":{"__StudentName":"John Smith"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39125ddae1f53b621f0")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"John Doe"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f39e25ddae1f53b621f1")
}
> db.nestedDemo.insertOne({"Information":{"__StudentName":"Chris Brown"}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06f3a625ddae1f53b621f2")
} 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.nestedDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e06f39125ddae1f53b621f0"),
"Information" : {
"__StudentName" : "John Smith"
}
}
{
"_id" : ObjectId("5e06f39e25ddae1f53b621f1"),
"Information" : {
"__StudentName" : "John Doe"
}
}
{
"_id" : ObjectId("5e06f3a625ddae1f53b621f2"),
"Information" : {
"__StudentName" : "Chris Brown"
}
} Đây là truy vấn tìm kiếm một tập hợp để tìm một giá trị được lồng vào một trong các tài liệu của nó trong MongoDB -
> db.nestedDemo.find({"Information.__StudentName":"John Doe"}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e06f39e25ddae1f53b621f1"), "Information" : { "__StudentName" : "John Doe" } }