LynAs
LynAs

Reputation: 6567

MongoDB query inside a nested array

I have the following collection in MongoDB:

{
  "id": 123,
  "profile":{
    "name": "name",
    "age":45,
    "wishlist": [
        {"_id":1, "name":"a1"},
        {"_id":2, "name":"a2"},
        {"_id":3, "name":"a3"}
      ]
  }
}

What is the query in the Mongo Shell to find if wishlist has collection where _id = 2 ?

Upvotes: 1

Views: 1258

Answers (1)

Sylvain Leroux
Sylvain Leroux

Reputation: 52040

As you ony match against one field, you only have to express the path to your field using dot-notation:

> db.user.find({"profile.wishlist._id": 2})

As explained in the MongoDB documentation, for arrays (like wishlist) this will match a document if any subdocument in the array match the field value.


Please note that if you need to match against several fields, you need to use either:

  • $elemMatch if all matching fields should belong to the same subdocument;
  • or multiple fields expressed using the dot-notation if the various fields don't need to match against the same subdocument.

Please compare the output of those two queries to get a grasp on this:

> db.user.find({"profile.wishlist._id": 2, "profile.wishlist.name": "a1"})
//                                      ^                            ^^
//                              will return your document even if the was no 
//                              subdocument having both _id=2 and name=a1
> db.user.find({"profile.wishlist": {$elemMatch: { _id: 2, name: "a1"}}})
//                                                      ^         ^^
//                                         no result as there was no subdocument
//                                         matching  _both_ _id=2 and name=a1

Upvotes: 5

Related Questions