Reputation: 117
I have the following collection
>db.prueba.find({})
{ "_id" : "A", "requi" : null }
{ "_id" : "B", "requi" : null }
{ "_id" : "C", "requi" : [ "A" ] }
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "E", "requi" : [ "C" ] }
{ "_id" : "F", "requi" : [ "B", "D"] }
{ "_id" : "G", "requi" : [ "F" ] }
I need each element of the requi field to be in the following array. in this case, the array has only one element
["A", "D"]
When I use the operator $all $in
returns the following
>db.prueba.find({requi:{$elemMatch:{$in:['A','D']}}})
{ "_id" : "C", "requi" : [ "A" ] }
{ "_id" : "D", "requi" : [ "A", "B" ] }
{ "_id" : "F", "requi" : [ "B", "D" ] }
the query must returns only document, because 'B'
not exists in the array ["A" , "D"]
{ "_id" : "C", "requi" : [ "A" ] }
please, help me
Upvotes: 1
Views: 57
Reputation: 46441
You can use $setIsSubset
to check whether the given array is set of the requi
array and then $redact
to eliminate the non-matched ones.
db.collection.aggregate([
{ "$match": { "requi": { "$ne": null } } },
{ "$redact": {
"$cond": {
"if": { "$eq": [{ "$setIsSubset": ["$requi", ["A", "D"]] }, true] },
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}}
])
Upvotes: 2