Hello I want to kno if is possible do a query for retrieve documents like this
Document
[
{
...
id:1
tags:['a', 'b', 'c']
...
},
{
...
id:2
tags:['b', 'c']
...
},
{
...
id:3
tags:['d']
...
}
]
findone({tags:{$all:['a', 'b']}})
-> 1 because a and b are only in doc 1
findone({tags:{$all:['b']}})
-> 1, 2 because b are only in doc 2
findone({tags:{$all:['a', 'b', 'd']}})
-> nothing, because any document has all tags inside array
findone({tags:{$all:['d']}})
-> 3 because d are only in doc 3
There are any way of do this query?
Thanks
CodePudding user response:
Query
- you can use
$setDifference
- if empty (setDifference your_array "$tags") => tags has all the elements, and filter is true
aggregate(
[{"$match":
{"$expr":
{"$eq": [{"$setDifference": [["a", "b", "d"], "$tags"]}, []]}}}])
If you want to keep only the id
you can also add after $match
{"$project": {"_id" : 0,"id": 1}}