MongoDb使用数组键上的乘法更新数组元素

MongoDb使用数组键上的乘法更新数组元素,mongodb,Mongodb,我有一份mongo文件如下 { "id": "mongoId", "results": [ "score" : 80, "details": { "credit": 2, "creditPoints": 40, "creditScore": 0 } ] }

我有一份mongo文件如下

{
  "id": "mongoId",
  "results": [
    "score" : 80,
    "details": {
        "credit": 2,
        "creditPoints": 40,
        "creditScore": 0
    }
  ]
}
我想将所有文档更新为
creditScore
credit*creditPoints

到目前为止,我所尝试的是

db.match.updateMany({}, { "$set" : { "results.$[].details.creditScore":   {"$mul" : { "$results.details.credit": "$results.details.creditPoints" } } }}  );

直接更新不允许使用内部字段操作,您需要从MongoDB 4.2开始使用

  • $map
    迭代
    结果的循环
    数组
  • $multiply
    乘以
    积分
    积分
  • $mergeObjects
    详细信息
    对象与更新的
    信用评分
    字段合并
  • $mergeObjects
    将当前对象与更新的
    详细信息
    对象合并

db.match.updateMany({},
[
  {
    $set: {
      results: {
        $map: {
          input: "$results",
          in: {
            $mergeObjects: [
              "$$this",
              {
                details: {
                  $mergeObjects: [
                    "$$this.details",
                    {
                      creditScore: {
                        $multiply: [
                          "$$this.details.credit",
                          "$$this.details.creditPoints"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])