我有以下文件
{
"_id": ObjectId("5461363bdfef7c4800146f4b"),
"title": "Plant Overview",
"segments": [
{
"tagBindings": [
{
"id" : ObjectId("54ac12f4b4f22ec30153ea83"),
"tagType" : "Facility"
},
{
"id" : ObjectId("54999a0e899ab5530031535e"),
"tagType" : "Facility"
},
{
"id" : ObjectId("5498189c496623160068831c"),
"tagType" : "Facility"
}
],
"name": "Liberty Lofts - Solar Power Plant",
"id": ObjectId("54637850dfcbe62000a7eddf")
}
]
}
我想查找segments.tagBindings.id等于某些值且没有任何其他ID的记录。
我使用该查询:
db.ds_dashboards.find({"segments.tagBindings.id": {$in: [ObjectId("54ac12f4b4f22ec30153ea83"), ObjectId("54999a0e899ab5530031535e")]}})
它返回上面的文档。
但我不需要它,因为第三个segment.tagBindings.id是5498189c496623160068831c
id。
我应该如何更新查询?
您想使用聚合并利用$setIsSubset
运算符。因此,您的查询将如下所示:
> db.ds_dashboards.aggregate([
{ "$unwind": "$segments"},
{ "$unwind": "$segments.tagBindings" },
{ "$group": {
"_id": "$_id",
"tagBindings" : { "$addToSet": "$segments.tagBindings.id" }
}
},
{ "$project": {
"isValid": {
"$setIsSubset": [
"$tagBindings",
[ObjectId("54ac12f4b4f22ec30153ea83"),
ObjectId("54999a0e899ab5530031535e")]
]}
}
}
]);
{ "_id" : ObjectId("5461363bdfef7c4800146f4b"), "isValid" : false }
给定您的示例文档,如上所示,上面的查询将返回false。正如您所说,这是因为ObjectId("5498189c496623160068831c")
中不存在$tagBindings
。如果您修改该数组以包含said ObjectId
,则它将返回true。
然后可以添加一个match
子句以筛选出结果是否isValid
为假。最后一个子句看起来像这样:{ "$match": { "isValid": true } }
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句