Dinuka Thilanga
Dinuka Thilanga

Reputation: 4330

Match all elements in document array with input array

The db has documents as follows.

{
    id: 1,
    items: ["a", "b", "c"]
},
{
    id: 2,
    items: ["a", "b"]
},
{
    id: 3,
    items: ["a", "b", "c", "d"]
}

I need to get records that have all items should include in the input query.

If input ["a", "b", "c"] #1 and #2, should come. Because all items includes in the input. But not #3, because input has not "d".

If i use {query: {$in: ["a", "b", "c"]}} = all records is coming.

If i use {query: {$all: ["a", "b", "c"]}} = #1, #2 records is coming.

What is the query for this?

Upvotes: 0

Views: 44

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

You can use this one:

db.collection.aggregate([
   {
      $match: {
         $expr: {
            $eq: [
               "$items",
               { $setIntersection: ["$items", ["a", "b", "c"]] }
            ]
         }
      }
   }
])

Upvotes: 2

Related Questions