'MongoDB : How to update a new field value according to existing field value in each document?

I am working on a project and it currently goes through each document to edit the field and lags a lot.

{ "Name" : "Susie" , "This Semester" : 10 , "Last Semester" : 0 }
{ "Name" : "John" , "This Semester" : 20 , "Last Semester" : 0 }
...

I have documents like these where I want to take the value of this semester, and put it in last semester (which is different for every document), and make "This Semester" to 0 for which I am going through each document 1 by 1, then taking the value of this semester, putting it in last semester one by one, which makes the project very inefficient.

Is there a way to update all the documents in one go?



Solution 1:[1]

Perform the update with aggregation pipeline to allow getting the value from other field.

db.collection.update({},
[
  {
    $set: {
      "Last Semester": {
        $getField: "This Semester"
      },
      "This Semester": 0
    }
  }
])

Sample Mongo Playground

Solution 2:[2]

db.collection.find().forEach(function (item){
item.LastSemester = item.ThisSemester;
item.ThisSemester = 0;
db.collection.save(item)});

Try this snippet

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun
Solution 2 Tomov Nenad