MongoDB 查询:聚合 "findOne"

MongoDB query: aggregate with "findOne"

我正在尝试对 MongoDB 3.4 进行查询,我在其中为数组的一个特定元素添加了一个字段。对象示例:

    {
        "_id": 1,
        "people": [
            {
                "name": "Jhon Smith",
                "age": "30",
                "state": "NY"
            },{
                "name": "Clint Mercer",
                "age": "50",
                "state": "NY"
            },{
                "name": "Walter Smith",
                "age": "40",
                "state": "WI"
            }
        ]
    }

我想进行查询,我将在该文档中添加一个属性,其中第一个人的名字中包含“Smith”。示例:

    {
        "_id": 1,
        "people": [
            {
                "name": "Jhon Smith",
                "age": "30",
                "state": "NY"
            },{
                "name": "Clint Mercer",
                "age": "50",
                "state": "NY"
            },{
                "name": "Walter Smith",
                "age": "40",
                "state": "WI"
            }
        ],
        "firstSmith": {
            "name": "Jhon Smith",
            "age": "30",
            "state": "NY"
        }
    }

我已经有了我想要的文档的_id,但是我不明白如何进行这样的查询。我正在尝试将聚合与“$match”用于 id,然后使用“$addFields”,但我无法进行适用于该字段的查询以准确找到我想要的内容。我认为它类似于“findOne”查询,但我找不到适用于“$addFields”的任何内容。

Obs:我不希望“firstSmith”是一个内部只有一个“人”的数组,我希望它像示例中那样。

我很感激这方面的帮助。

  • $match - 过滤相关文档
  • $filter$regexMatch - 通过 name 属性[ 过滤 people 数组=26=]
  • arrayElemAt - 仅获取上述数组的第一个元素
  • $addFields - 添加具有上述结果
  • 值的新字段
db.collection.aggregate([
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$addFields": {
      "firstSmith": {
        "$arrayElemAt": [
          {
            "$filter": {
              "input": "$people",
              "cond": {
                "$regexMatch": {
                  "input": "$$this.name",
                  "regex": "Smith"
                }
              }
            }
          },
          0
        ]
      }
    }
  }
])

Working example