【问题标题】:Add field to every object in array of objects in mongo aggregation向mongo聚合中的对象数组中的每个对象添加字段
【发布时间】:2021-07-26 19:52:02
【问题描述】:

我在根级别的架构中有一个字段,并希望将其添加到数组中与条件匹配的每个对象中。

这是一个示例文档....

{
    calls: [
      {
        "name": "sam",
        "status": "scheduled"
      },
      {
        "name": "tom",
        "status": "cancelled"
      },
      {
        "name": "bob",
        "status": "scheduled"
      },
      
    ],
    "time": 1620095400000.0,
    "call_id": "ABCABCABC"
}

所需文件如下:

[
  {
    "call_id": "ABCABCABC",
    "calls": [
      {
        "call_id": "ABCABCABC",
        "name": "sam",
        "status": "scheduled"
      },
      {
        "name": "tom",
        "status": "cancelled"
      },
      {
        "call_id": "ABCABCABC",
        "name": "bob",
        "status": "scheduled"
      }
    ],
    "time": 1.6200954e+12
  }
]

call_id 应添加到数组中状态为“已调度”的所有对象。 是否可以使用 mongo 聚合来做到这一点?我试过$addFields,但无法达到上述结果。 提前致谢!

【问题讨论】:

    标签: mongodb aggregation


    【解决方案1】:

    这是我使用$map$mergeObjects 的方法

    db.collection.aggregate([
      {
        "$addFields": {
          calls: {
            $map: {
              input: "$calls",
              as: "call",
              in: {
                $cond: [
                  {
                    $eq: [
                      "$$call.status",
                      "scheduled"
                    ]
                  },
                  {
                    "$mergeObjects": [
                      "$$call",
                      {
                        call_id: "$call_id"
                      }
                    ]
                  },
                  "$$call"
                ]
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多