将字段添加到mongo聚合中对象数组中的每个对象

时间:2021-05-04 12:58:21

标签: mongodb aggregation

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

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

{
    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 但无法达到上述结果。 提前致谢!

1 个答案:

答案 0 :(得分: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