Prashant Solanki
Prashant Solanki

Reputation: 102

How to query on array field with an aray in mongodb?

Example of a document in a dummy collection.

{
    "_id": "1",
    "subjects": ['English', 'Maths', 'Science', 'French',..]
}

Now I want to select all the documents which are having any of the subjects mentioned in an array. Eg: ['Maths', 'French'].

So the result of the query should give all the documents wherever any of the subjects that are mentioned.

Therefore for the above examples, all the document's which are having Maths or French subjects should be returned.

Upvotes: 1

Views: 39

Answers (1)

varman
varman

Reputation: 8894

You can use $in operator with find() or aggregate()

db.collection.find({
  "subjects": {
    $in: [
      "English"
    ]
  }
})

Or

db.collection.aggregate([
  {
    $match: {
      subjects: {
        $in: [
          "Maths",
          "English"
        ]
      }
    }
  }
])

Working Mongo playground

Upvotes: 1

Related Questions