MongoDB

Modify Documents using Mongo Shell

MongoDB provides the update() method to update the documents of a collection. The method accepts as its parameters:

  • an update conditions document to match the documents to update,
  • an update operations document to specify the modification to perform, and
  • an options document.

To specify the update condition, use the same structure and syntax as the query conditions.

 > db.users.update( { Name : "Himen Patel" }, {$set : { "Email" : "admin@dotnet-fundamentals.com"} })   

A successful update of the document returns the following object:

 WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })  


Update multiple documents.
By default, the update() method updates a single document. To update multiple documents, use the multi option in the update() method.

 db.users.update( { Name : "Himen Patel" }, {$set : { "Email" : "admin@dotnet-fundamentals.com"} }, {multi: true})  

A successful update of the document returns the following object.

 WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })  

Leave a comment