确切路径未知时在MongoDb中搜索字段

时间:2015-01-12 06:38:25

标签: mongodb mongodb-query

我在Mongo有一个结构已知的集合。 它由

组成
{
    "_id" : "123456__data",
    "fields" : {
        "field1" : {
            "type" : "boolean",
            "writeAccess" : "someWriteAccess",
        },
        "field2" : {
            "type" : "integer",
            "writeAccess" : "secondWriteAccess",
        },
        "field3" : {
            "someConcretePermissionOperation" : "set",
            "writeAccess" : "thirdWriteAccess",
        }
    }
}

现在我需要找到所有文档,最好是所有具体的值" someConcretePermissionOperation",而" field1",2,3可以由用户决定。也就是说,在不同的文档中,它们可以有不同的名称。我唯一知道的是持续深度 - 如果someConcretePermissionOperation出现,它将在fields.XXX.someConcretePermissionOperation下,其中XXX可以是任何东西。

有人有任何想法吗?

刚刚找到了我正在寻找的东西:

var operationOptions = [ "push", "set", "pushUnique" ];
db.mytable.aggregate(
   [
     { $redact:
         {
            $cond:
               {
                 if: { $gt: [ { $size: { $setIntersection: [ "$someConcretePermissionOperation", operationOptions ] } }, 0 ] },
                 then: "$$DESCEND",
                 else: "$$PRUNE"
               }
         }
     }
   ]
)

但收到了 uncaught exception: aggregate failed: { "errmsg" : "exception: The argument to $size must be an Array, but was of type: NULL",

完全不知道怎么写"如果存在,否则无视"在此聚合查询中。

1 个答案:

答案 0 :(得分:2)

使用 $ifNull 运算符检查字段是不是数组还是不存在:

var operationOptions = [ "push", "set", "pushUnique" ];
db.mytable.aggregate(
   [
     { $redact:
         {
            $cond:
               {
                 if: { 
                    $gt: [ 
                        { 
                            $size: { 
                                "$ifNull": [
                                    { $setIntersection: ["$someConcretePermissionOperation", operationOptions] },
                                    []
                                ]
                            } 
                        }, 
                        0 
                    ] 
                },
                 then: "$$DESCEND",
                 else: "$$PRUNE"
               }
         }
     }
   ]
)