1

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 ?

1 Answer 1

5

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
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.