嵌套数组内的 MongoDB 查询 [英] MongoDB query inside a nested array

查看:95
本文介绍了嵌套数组内的 MongoDB 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MongoDB 中有以下集合:

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"}
      ]
  }
}

在 Mongo Shell 中查找 wishlist 是否有集合 where _id = 2 的查询是什么?

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

推荐答案

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

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})

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

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 如果所有匹配的字段都应该属于相同子文档;
  • 多个字段,如果各个字段不需要匹配同一个子文档,则使用点符号表示.
  • $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

这篇关于嵌套数组内的 MongoDB 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆