Update array element with field value of document

Hi
I do have collection called “student” which has following data (provided in json format).

I can update the “grade” in grades array by using

db.students.updateMany({},{inc:{"grades..grade":-5}})

but instead of “-5” I want to use “adj” field of document . How can I do that?
I tried to use

db.students.updateMany({},{inc:{"grades..grade":’$adj’}})

but I am getting error

{
  "_id": 1,
  "adj": -5,
  "grades": [
    {
      "grade": 70,
      "mean": 75,
      "std": 6
    },
    {
      "grade": 75,
      "mean": 90,
      "std": 4
    },
    {
      "grade": 75,
      "mean": 85,
      "std": 6
    }
  ]
},{
  "_id": 2,
  "adj": -4,
  "grades": [
    {
      "grade": 80,
      "mean": 75,
      "std": 6
    },
    {
      "grade": 77,
      "mean": 90,
      "std": 3
    },
    {
      "grade": 75,
      "mean": 85,
      "std": 4
    }
  ]
}

Thanks

Hi @Dhruvesh_Patel,

I think you should be able to use aggregation pipeline update with $add instead of the $inc.

https://docs.mongodb.com/manual/tutorial/update-documents-with-aggregation-pipeline/

Thanks
Pavel

1 Like

I am sorry , I have tried few different variations and it’s not working. Is it possible you can provide working example of it?

thanks

@Dhruvesh_Patel,

You can do something like this, $map to iterate loop of grades array, $add to sum grade and adj fields, $mergeObjects to merge current object with updated grade field

db.students.updateMany({},
[{
    $set: {
      grades: {
        $map: {
          input: "$grades",
          in: {
            $mergeObjects: [
              "$$this",
              { grade: { $add: ["$$this.grade", "$adj"] } }
            ]
          }
        }
      }
    }
}])
1 Like

Thanks it works. It’s compatible with mongodb version 4.2 but not with 4.0

1 Like

You are right it is starting from MongoDB v4.2.