查找 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