MongoDB:聚合函数中的映射嵌套数组

时间:2020-05-18 16:08:30

标签: mongodb mongodb-query aggregation-framework

我正在尝试通过使用聚合来更新属性名称。当前文档

[
  {
    _id: 5,
    payLoad: {
      grades: [
        {
          grade_: 80,
          mean: 75
        },
        {
          grade_: 90,
          mean: 80

        }
      ]
    }
  }
]

预期文档将grade_重命名为grade

[
      {
        _id: 5,
        payLoad: {
          grades: [
            {
              grade: 80,
              mean: 75
            },
            {
              grade: 90,
              mean: 80

            }
          ]
        }
      }
    ]

为此,我正在尝试映射聚合

db.collection.aggregate([
  {
    $addFields: {
      payLoad: {
        grades: {
          $map: {
            input: "$grades",
            as: "grade",
            in: {
              grade: "$$grade.grade_",
              mean: "$$grade.mean"
            }
          }
        }
      }
    }
  }
])

这不起作用。不确定此映射是否正确

payLoad: {
            grades: {

还尝试了像payLoad.grades

这样的映射

1 个答案:

答案 0 :(得分:1)

这应该有效。

{
    $addFields: {
        "payLoad.grades": {
            $map: {
                input: "$payLoad.grades",
                as: "grade",
                in: {
                    grade: "$$grade.grade_",
                    mean: "$$grade.mean"
                }
            }
        }
    }
}