Tlaloc-ES
Tlaloc-ES

Reputation: 5282

how to find documents with all elements in the array in the document?

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

Upvotes: 0

Views: 32

Answers (1)

Takis
Takis

Reputation: 8693

Query

  • you can use $setDifference
  • if empty (setDifference your_array "$tags") => tags has all the elements, and filter is true

Test code here

aggregate(
[{"$match": 
    {"$expr": 
      {"$eq": [{"$setDifference": [["a", "b", "d"], "$tags"]}, []]}}}])

Upvotes: 1

Related Questions