skip to Main Content

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?

2

Answers


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

    Try this snippet

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search