Home > Net >  MongoDB : How to update a new field value according to existing field value in each document?
MongoDB : How to update a new field value according to existing field value in each document?

Time:05-13

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?

CodePudding user response:

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

CodePudding user response:

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

Try this snippet

  • Related