how to return objects from filtering of nested arrays in mongodb?

You need nested $elemMatch to get the result you want

The query is like this:

db.collection.find({
  "categories": {
    "$elemMatch": {
      "$elemMatch": {
        "$in": [
          "Books",
          "Quick & Easy",
          "Cookbooks, Food & Wine"
        ]
      }
    }
  }
})

Basically is find into categories and query a nested elemMatch to raise the nested array. Into the nested array, is only neccesary look for $in.

Example here

Note that this query will return the entire document that match any value into $in array.

Another example with more documents (and only categories field) to see clearer how the query works.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top