Prabsimar Chhabra
Prabsimar Chhabra

Reputation: 21

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?

Upvotes: 2

Views: 1890

Answers (2)

Yong Shun
Yong Shun

Reputation: 51125

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

Upvotes: 3

Tomov Nenad
Tomov Nenad

Reputation: 164

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

Try this snippet

Upvotes: 0

Related Questions