MongoDB – Update Document

To update the documents in a collection, MongoDB provides the update() method. To only update specific documents, add a condition to the update statement.

In this article, we will understand how to update a document in MongoDB using the update() method, save () method, updateOne() method and updateMany() method with examples for each. We will also look at the differences between each of these methods. 

Updating Single document 

Syntax: db.collection.update(query, update, options) 

  1. Use the update method  
  2. Specify the condition to be used to update the document. In the below example, we need to update the document which has the Employee id as 100. 
  3. Use the $set operator to update the values  
  4. Choose the Field Name that needs to be updated and enter the new values accordingly –  
Employee_Name =”Daniel Morales”
db.Employees.update(
{"Emp_ID" :100},
{$set:{"Employee_Name" :"Daniel Morales"}});
WriteResult({"nMatched": 1,  "nUpserted: 0, "nModified":1 })

Updating Multiple documents 

Syntax: db.collection.update(query, update, options) 

For updating multiple documents at the same time in MongoDB, we need to use the multi-option, or else by default only one document is updated at a time.

The below example shows how to update many documents. In this example, we are going to first find the document which has the Emp_ID id as “1” and then change the Emp_ID from 1 to 21 and Employee_Name to “Nandan Kumar”. 

  1. Use the update method  
  2. Specify the condition which should be used for updating the document. In the below example, we need to update the document which has the Employee id as 1. 
  3. Use the $set operator to update the values  
  4. Choose the Field Name(s) that needs to be updated and enter the new values accordingly – 
Employee_Name =”Nandan Kumar”
Emp_ID = 21
db.Employees.update({ Emp_ID : 1},{$set :{"Employee_Name" : "Nandan Kumar"," Emp_ID" : 21}})

MongoDB save() Method  

The db.collection.save() method is used to update an existing document or insert a new document 

Syntax: db.collection.save() 

db.Employees.save( {Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({“ nInserted" : 1 })

The save() method returns a WriteResult object which contains the status of the insert or update operation. 

During the insert, the shell will create the _id field with a unique ObjectId value, as verified by the inserted document:

db.Employees.find();
{"_id" : ObjectId("5da78973835b2f1c75347a83"),"Emp_ID" : 21000 , "Employee_Name" : "Anshu", "Salary":20000 }

In the below example, save() method performs an insert since the document passed to the method does not contain the _id field so it creates a new document . 

Note –  If the document doesn’t contain an _id field, then the save() method calls the insert() method. 

db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({"nMatched": 0,  "nUpserted: 1, "nModified":0,”_id”:2400})

The save() method performs an update with upsert: true since the document contains an _id field:  

db.Employees.save({_id:2400, Emp_ID : 21000 , Employee_Name : "Anshu", Salary:20000 } ); 
WriteResult({"nMatched": 1,  "nUpserted: 1, "nModified":0 })

Note –  

If the document already contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field. 

Updating Single and Multiple Values in MongoDB documents by using methods  -updateOne, updateManywith examples : 

MongoDB updateOne() method 

This method updates a single document within a collection matching the filter or condition. 

Syntax 

The syntax of updateOne() method is − 

db.collection.updateOne(, ) 

Example

> db.Employees.updateOne(
{First_Name: 'Nandan'},
{ $set: { Age: '30',e_mail: 'nandan@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

MongoDB updateMany() method 

The updateMany() method updates all the documents within a collection based on the filter or condition . 

Syntax : 

The syntax of updateMany() method is − 

db.collection.updateMany(, ) 

Example

>db.Employees.updateMany( 
{Age:{ $gt:"25"}}, 
{ $set:{Age:'12'}} 
) 
{"acknowledged":true,"matchedCount":2,"modifiedCount":2}

Using the find command, you can retrieve the contents of the documents: 

> db.Employees.find() 
{ "_id" : ObjectId("6fd6636870fb13eec3963bf5"), "First_Name" : "Nandan", "Last_Name" : "Kumar", "Age" : "12", "e_mail" : "nandan@gmail.com", "phone" : "8000012345
{ "_id" : ObjectId("6fd6636870fb13eec3963bf6"), "First_Name" : "Chris", "Last_Name" : "Goel", "Age" : "12", "e_mail" : "chris@gmail.com", "phone" : "8000054321" } 
{ "_id" : ObjectId("6fd6636870fb13eec3963bf7"), "First_Name" : "Praveen", "Last_Name" : "Sharma", "Age" : "21", "e_mail" : "praveen@gmail.com", "phone" : "9000011111" }

What If the update operation doesn’t match documents in collection? 

If the update operation doesn’t match any documents in the collection, it can automatically insert a new document into the collection which matches the update query by setting the upsert option as true.

db.Employees.update(
{type:"FullTime"},
{$set:{salary:20000}},
{upsert : true}
)

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

You can also see the upsert getting reflected in the Write Result of the above operation. 

upsert operation in MongoDB is used to save documents into collection . 

If the document matches query criteria, then it will perform an update operation or else it will insert a new document into the collection. 

Difference between db.collection.update() , db.collection.update One() and db.collection.update Many() 

The difference is that update() by default, modifies only one document based on the specified filter. However, the user can modify all the documents by adding the modifier {multi: true}. 

This command works as both updateOne and updateMany commands. 

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" },
   }
)

Here, it will update only the first document which matches the condition.

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" },
   },
{ multi: true } // Additional Parameter
)

Here, by adding the parameter – multi: true it works as updateMany() and updates all the documents matching the condition .

db.collection.updateOne() –> method to update only one document in a collection.

db.Employees.update (
   { "joinYear ": "2020" },
   {
     $set: { "bonusEligiblity": "False" }, // Here multiple parameters can also be updated  
   }
)

This update commands use the joinDate =2020 as a filter (match the query) in the collection “Employees”. $set operator (called as update operator) updates the value of the bonusEligiblity to False.


You can also update multiple parameters but they need to be separated by a comma (,). E.g.

$set: { "bonusEligiblity": "False" , “emp_status : ”New”},

db.collection.updateMany() –> method to update multiple document in a collection matching the specified condition

db.Employees.updateMany(
   { "joinYear": "2020" },
  {
$set: { "bonusEligiblity": "False" },
  }
)

Here, ALL the documents having joinYear =2020 get updated to bonus Eligiblity= “False” 

What If the update operation doesn’t match documents in the collection? 

If the update operation does not match any documents in the collection, it can automatically insert a new document that matches the update query into the collection by setting the upsert option to true.

db.Employees.update( 
    {type:"FullTime"}, 
    {$set:{salary:20000}}, 
    {upsert : true} 
 )

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

You can also see the upsert getting reflected in the WriteResult of the above operation.

upsert operation in MongoDB is used to save documents into a collection.

If the document matches query criteria then it will perform an update operation or else it will insert a new document into the collection.
In MongoDB, upsert also partially updates an object, so that the new object will overlay or merge with the existing one.

In summary, upsert is used to update a document with the contents of another document, but it only updates the fields that are missing and ignores the fields that are already set.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *