Bạn có thể sử dụng find () cho việc này. 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.findDocumentsDemo.insertOne(
{
_id: 101,
"ProductDetails": [
{ "ProductValue":100 },
{ "ProductValue":120 }
]
}
);
{ "acknowledged" : true, "insertedId" : 101 }
> db.findDocumentsDemo.insertOne(
{
_id: 102,
"ProductDetails": [
{ "ProductValue":120},
{ "ProductValue":120 },
{ "ProductValue":120 }
]
}
);
{ "acknowledged" : true, "insertedId" : 102 } 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.findDocumentsDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : 101,
"ProductDetails" : [
{
"ProductValue" : 100
},
{
"ProductValue" : 120
}
]
}
{
"_id" : 102,
"ProductDetails" : [
{
"ProductValue" : 120
},
{
"ProductValue" : 120
},
{
"ProductValue" : 120
}
]
} Sau đây là truy vấn để tìm tài liệu trong đó tất cả các phần tử của một mảng có giá trị cụ thể, tức là ProductValue 120 tại đây -
> db.findDocumentsDemo.find({
"ProductDetails.ProductValue" : {
},
"ProductDetails" : {
$not : {
$elemMatch : {
"ProductValue" : {
$ne : 120
}
}
}
}
}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }