meteor - MongoDB query inside a nested array -


i have 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 query in mongo shell find if wishlist has collection _id = 2 ?

as ony match against one field, have express path field using dot-notation:

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

as explained in mongodb documentation, arrays (like wishlist) match document if any subdocument in array match field value.


please note if need match against several fields, need use either:

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

please compare output of 2 queries grasp on this:

> db.user.find({"profile.wishlist._id": 2, "profile.wishlist.name": "a1"}) //                                      ^                            ^^ //                              return document if no  //                              subdocument having both _id=2 , name=a1 
> db.user.find({"profile.wishlist": {$elemmatch: { _id: 2, name: "a1"}}}) //                                                      ^         ^^ //                                         no result there no subdocument //                                         matching  _both_ _id=2 , name=a1 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -