使用 MongoDB 聚合基于另一个现有数组创建元素数组

问题描述 投票:0回答:1

我需要从文档中获取一个字段作为输入,如下所示:

"participants": ["John", "Peter"],

并使输出字段像这样:

"participants": [
    {
        "name": null,
        "identifier": "John",
        "type": "individual",
    },
    {
        "name": null,
        "identifier": "Peter",
        "type": "individual",
    },
]

基本上,这个想法是获取数组的每个元素并用具有多个字段的结构/映射“替换它”。

我尝试通过展开参与者字段并重新组合将字段推入新结构的所有内容来做到这一点,但肯定有更好的方法来做到这一点......对吗?

mongodb mongodb-query aggregation-framework pymongo
1个回答
0
投票

使用

$map
迭代数组并增加条目,通过聚合管道进行更新。

db.collection.update({},
[
  {
    "$set": {
      "participants": {
        "$map": {
          "input": "$participants",
          "as": "p",
          "in": {
            "name": null,
            "identifier": "$$p",
            "type": "individual"
          }
        }
      }
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.