【问题标题】:How to query two fields on same nested document [duplicate]如何查询同一个嵌套文档上的两个字段[重复]
【发布时间】:2021-08-18 20:39:07
【问题描述】:

我怎样才能只得到第二个文件,有孩子{"name": "Harry", "age": 20}

我尝试查询 db.items.find({"children.name": "Harry", "children.age": 20}),但它在子项中搜索单个字段匹配而不是两者

[
  {
    "children": [
      {
        "name": "Harry",
        "age": 50
      },
      {
        "name": "Dmitry",
        "age": 20
      }
    ]
  },
  {
    "children": [
      {
        "name": "Harry",
        "age": 20
      }
    ]
  }
]

【问题讨论】:

  • 使用$elemMatch 匹配数组元素。
  • @turivishal 请添加一个答案,这样我可以选择它作为正确的一个
  • 这是一个常见问题,有很多类似的问题,所以我投票结束这个问题。

标签: mongodb


【解决方案1】:
db.items.aggregate([
    {
        $match:
        {
            "children":
            {
                $elemMatch:
                {
                    "name": "Harry",
                    "age": 20
                }
            }
        }
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 2018-09-04
    • 2021-06-01
    • 1970-01-01
    • 2016-07-17
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多