查詢 MongoDB 中具有特定值的所有陣列元素的文件?
你可以使用 find() 來實現。讓我們首先使用文件建立一個集合 -
> 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 }以下是使用 find() 方法顯示集合中所有文件的查詢 -
> db.findDocumentsDemo.find().pretty();
這將生成以下輸出 -
{
"_id" : 101,
"ProductDetails" : [
{
"ProductValue" : 100
},
{
"ProductValue" : 120
}
]
}
{
"_id" : 102,
"ProductDetails" : [
{
"ProductValue" : 120
},
{
"ProductValue" : 120
},
{
"ProductValue" : 120
}
]
}以下是查詢擁有特定值的陣列所有元素的文件的查詢,這裡值為 ProductValue 120 -
> db.findDocumentsDemo.find({
"ProductDetails.ProductValue" : {
},
"ProductDetails" : {
$not : {
$elemMatch : {
"ProductValue" : {
$ne : 120
}
}
}
}
});這將生成以下輸出 -
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP