Finding a field in MongoDb when exact path is unknown
I have a collection in Mongo where the structure is known. It consists of
{
"_id" : "123456__data",
"fields" : {
"field1" : {
"type" : "boolean",
"writeAccess" : "someWriteAccess",
},
"field2" : {
"type" : "integer",
"writeAccess" : "secondWriteAccess",
},
"field3" : {
"someConcretePermissionOperation" : "set",
"writeAccess" : "thirdWriteAccess",
}
}
}
Now I need to find all the docs and preferably all the specific values โโof "someConcretePermissionOperation", while "field1", 2, 3 may be up to the user. That is, they may have different names in different documents. The only thing I know is constant depth - if someConcretePermissionOperation appears, it will be under fields.XXX.someConcretePermissionOperation
, where XXX could be anything.
Does anyone have any idea?
Just found something close to what I'm looking for:
var operationOptions = [ "push", "set", "pushUnique" ];
db.mytable.aggregate(
[
{ $redact:
{
$cond:
{
if: { $gt: [ { $size: { $setIntersection: [ "$someConcretePermissionOperation", operationOptions ] } }, 0 ] },
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
)
But getting
uncaught exception: aggregate failed: {
"errmsg" : "exception: The argument to $size must be an Array, but was of type: NULL",
Don't know yet how to write "if exists, otherwise ignore" in this aggregation query.
source to share
Use an operator to check if this field is not an array or not: $ifNull
var operationOptions = [ "push", "set", "pushUnique" ];
db.mytable.aggregate(
[
{ $redact:
{
$cond:
{
if: {
$gt: [
{
$size: {
"$ifNull": [
{ $setIntersection: ["$someConcretePermissionOperation", operationOptions] },
[]
]
}
},
0
]
},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
)
source to share