0

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?

2
  • The two queries are exactly the same, I doubt they give different results. Commented Apr 2, 2020 at 6:01
  • Sorry, I modified it. Commented Apr 2, 2020 at 6:04

1 Answer 1

2

You can use this one:

db.collection.aggregate([
   {
      $match: {
         $expr: {
            $eq: [
               "$items",
               { $setIntersection: ["$items", ["a", "b", "c"]] }
            ]
         }
      }
   }
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.