Update documents in MongoDB

Update documents in MongoDB

In order to update a document we use the method "update", "updateOne" or "updateMany". The update method takes 3 parameters

Update parameters

  • Query: which objects you want to update and it has the same syntax as find. [Query operators]
  • Update: fields to update using update operators. [Fields, Array and Modifiers update operators in MongoDB]
  • Object: additional data that concern the update like
    • upsert (boolean): insert the element if not found
    • multi (boolean): update multiple document at once

Update examples

Update all the document with the new values except the id

> db.test.update({name: "something"}, {name: "edited", "field2": "value"})

Update only the nessacery fields and save the other fields

> db.test.update({name: "edited"}, {$set: {name: "somthing2"}})

Update all document

> db.test.updateMany({}, {$set: {name: "somthing2"}})
  • The main difference between update and (updateMany and updateOne) is that with the last two you can't update all the document at once or you'll get the error: uncaught exception: Error: the update operation document must contain atomic operators
  • The difference between update with default options (multi equal false) and updateMany is that update only modify the first document found

Update with upsert parameter

When the value of upsert is set to true when using update, if no document exists MongoDB will create that document for you.

Update all document

db.test.update({name: "not-exist"}, {$set: {views: 0, tags: ["undefined"]}}, {upsert: true})
{ "_id" : ObjectId("5e3c9d59db436e5aab89a7b1"), "name" : "not-exist", "tags" : [ "undefined" ], "views" : 0 }