Để nhận các phần tử cụ thể, hãy sử dụng $ match với 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.demo641.insert(
... {
... ProductId:101,
... "ProductInformation":
... ( [
... {
... ProductName:"Product-1",
... "ProductPrice":1000
... },
... {
... ProductName:"Product-2",
... "ProductPrice":500
... },
... {
... ProductName:"Product-3",
... "ProductPrice":2000
... },
... {
... ProductName:"Product-4",
... "ProductPrice":3000
... }
... ]
... }
... );
WriteResult({ "nInserted" : 1 }) 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.demo641.find();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"), "ProductId" : 101, "ProductInformation" :
[
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
} Sau đây là truy vấn để lấy các phần tử cụ thể từ mảng được nhúng trong MongoDB
> db.demo641.aggregate([
... {$unwind: "$ProductInformation"},
... {$match: { "ProductInformation.ProductPrice": {$in :[1000, 2000]}} },
... {$project: {_id: 0, ProductInformation: 1} }
... ]).pretty(); Điều này sẽ tạo ra kết quả sau -
{
"ProductInformation" : {
"ProductName" : "Product-1",
"ProductPrice" : 1000
}
}
{
"ProductInformation" : {
"ProductName" : "Product-3",
"ProductPrice" : 2000
}
}