MongoDb update array element with multiply on array keys

Viewed 73

I have a mongo document as follows

{
  "id": "mongoId",
  "results": [
    "score" : 80,
    "details": {
        "credit": 2,
        "creditPoints": 40,
        "creditScore": 0
    }
  ]
}

I want to update all documents the creditScore as credit * creditPoints.

What i have tried till now is

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

Direct update is not allow to use internal fields operations, you need to use update with aggregation pipeline starting from MongoDB 4.2,

  • $map to iterate loop of results array
  • $multiply to multiply credit and creditPoints
  • $mergeObjects to merge details object with updated creditScore field
  • $mergeObjects to merge current object with updated details object
db.match.updateMany({},
[
  {
    $set: {
      results: {
        $map: {
          input: "$results",
          in: {
            $mergeObjects: [
              "$$this",
              {
                details: {
                  $mergeObjects: [
                    "$$this.details",
                    {
                      creditScore: {
                        $multiply: [
                          "$$this.details.credit",
                          "$$this.details.creditPoints"
                        ]
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
])

Playground

Related