Sudip Bolakhe
Sudip Bolakhe

Reputation: 523

Mongo db : Query on array that matches any elemet of another passed array

There are documents like:

{ _id:1, color:['red', 'green', 'yellow'},
{ _id:2, color:['red', 'blue', 'orange'},
{ _id:3, color:['blue', 'black', 'grey'}

Now what I am trying to do is : If I passed ['red']

It should return document with id 1 and 2. If I passed ['black', 'yellow'], it should return document with id 1 and 3.

Upvotes: 0

Views: 566

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

You can use $elemMatch to get what you want.

Try this:

db.collection.find({
  color: {
    $elemMatch: {
      $in: [
        "black",
        "yellow"
      ]
    }
  }
})

Have a look at this Mongo Playground demo, to play with the query.

Upvotes: 3

Related Questions