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.embeddedDocumentDemo.insertOne(
... {
... "CustomerDetails":[
... {"CustomerName":"Chris", "CustomerPurchasePrice":3000},
... {"CustomerName":"Robert", "CustomerPurchasePrice":4500},
... {"CustomerName":"David", "CustomerPurchasePrice":1000},
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd32347edc6604c74817ccd")
} 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.embeddedDocumentDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd32347edc6604c74817ccd"),
"CustomerDetails" : [
{
"CustomerName" : "Chris",
"CustomerPurchasePrice" : 3000
},
{
"CustomerName" : "Robert",
"CustomerPurchasePrice" : 4500
},
{
"CustomerName" : "David",
"CustomerPurchasePrice" : 1000
}
]
} Sau đây là truy vấn cho tài liệu nhúng -
> db.embeddedDocumentDemo.find({"CustomerDetails.CustomerPurchasePrice":4500}); Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd32347edc6604c74817ccd"),
"CustomerDetails" : [
{
"CustomerName" : "Chris",
"CustomerPurchasePrice" : 3000
},
{
"CustomerName" : "Robert",
"CustomerPurchasePrice" : 4500
},
{
"CustomerName" : "David",
"CustomerPurchasePrice" : 1000
}
]
}