嵌套数组中的MongoDB查询

Lyn*_*nAs 1 mongodb meteor

我在MongoDB中有以下集合:

{
  "id": 123,
  "profile":{
    "name": "name",
    "age":45,
    "wishlist": [
        {"_id":1, "name":"a1"},
        {"_id":2, "name":"a2"},
        {"_id":3, "name":"a3"}
      ]
  }
}
Run Code Online (Sandbox Code Playgroud)

Mongo Shell中的查询是什么,以查找是否wishlist有集合在哪里_id = 2

Syl*_*oux 5

当你匹配一个字段时,你只需要用点符号表示你的字段的路径:

> db.user.find({"profile.wishlist._id": 2})
Run Code Online (Sandbox Code Playgroud)

正如MongoDB文档中所解释的,对于数组(如wishlist),如果数组中的任何子文档与字段值匹配,则它将匹配文档.


请注意,如果您需要匹配多个字段,则需要使用以下任一字段:

  • $elemMatch如果所有匹配的字段都属于同一个子文档;
  • 多个字段使用点符号,如果各个领域并不需要匹配对同一子文档表示.

请比较这两个查询的输出以掌握这个:

> 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
Run Code Online (Sandbox Code Playgroud)
> db.user.find({"profile.wishlist": {$elemMatch: { _id: 2, name: "a1"}}})
//                                                      ^         ^^
//                                         no result as there was no subdocument
//                                         matching  _both_ _id=2 and name=a1
Run Code Online (Sandbox Code Playgroud)