在 MongoDB 中查找数组中所有元素都具有特定值的文档?\
mongodbdatabasebig data analytics更新于 2026/1/16 9:22:17
您可以使用 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 } ] }

