【问题标题】:MongoDB query: aggregate with "findOne"MongoDB 查询:与“findOne”聚合
【发布时间】:2022-01-12 00:28:48
【问题描述】:

我正在尝试在 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”是一个只有一个“人”的数组,我希望它与示例中的一样。

我希望能得到一些帮助。

【问题讨论】:

    标签: mongodb mongodb-query nosql aggregation-framework


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

    Working example

    【讨论】:

    • 它不适用于我的 MongoDB 版本,但我认为通过这种改编它可能会起作用。 stackoverflow.com/questions/68066925/… 无论哪种方式,我都会标记为已解决,因为在较新的版本上它可以工作。谢谢 =)
    猜你喜欢
    • 2014-03-06
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多