Home  >  Blog  >   MongoDB

MongoDB Update Document

Rating: 5
  
 
10448

In today’s article, we will be focusing on the Update command within MongoDB. As this is not a traditional SQL database we need to pay extra attention and efforts to understand how an Update statement works in this case.

MongoDB Update Document

With the use of the Update method, an individual can update a specific field within the document or they can completely update an existing document. This can be achieved based on the Update parameters used. We will go through these scenarios with relevant examples at a later part of this article.

If you want to enrich your career and become a professional in MongoDB, then visit Mindmajix - a global online training platform: "MongoDB Training" This course will help you to achieve excellence in this domain. 

Definition 

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

As per the default update() method, a single document can be updated. If “Multi-Parameter” is acknowledged in the syntax then the update method will update all the documents as per the query.

db.collection.update(
  ,
  ,
  {
    upsert: ,
    multi: ,
    writeConcern: ,
    collation:
  }
)

Note: Code snippet has been taken from MongoDB official documentation.

Parameter's

 Parameter
 Query
 Description
 query document This part describes the selection criteria of the document that needs to be updated
 update   document Whatever the documents needed to be updated,  this parameter will be the key and it will do the job
 upsert boolean If the upsert is set to true, If no documents are matched based on the query selection, a new document will be created. If the upsert is set to false, which is a default way. Based on the query selection, if documents are matched then only the information will be updated.
 multi boolean If this parameter is set to true, then it will update multiple documents that meet the query criteria or selection. If this parameter is set to false, then it will update only a single document. The default value for this parameter is always false.
Write concern document It is an optional parameter
collation document It is an optional parameter

MindMajix Youtube Channel

MongoDB Update One:

Let’s consider the below example as a way to walk you through a single document update within MongoDB.

The school collection contains the following documents:

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan" },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

The above data set is available within the database as of now.

Now we are writing an update statement to include “Violations” as another data field the first record with the name “International School”.

try {
  db.school.updateOne(
     { "name" : "International School" },
     { $set: { "violations" : 4 } }
  );
} catch (e) {
  print(e);
}

So based on the above query, if it is processed.

If there is any data matched, then the below statement will appear confirming the data has been updated.

{acknowledged”: true, “matchedCount”:1 , “modifiedCount” :1}

If the data didn’t match then the below statement will appear confirming the data has not been updated.

{acknowledged” : true, “matchedCount” :0 , “modifiedCount”  :0}

So after the update, the school collection documents within MongoDB will be something like this:

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4 },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

Now let’s try to understand and update a document within MongoDB using Upsert as a parameter, set to true:

As said, setting this parameter will update the document within MongoDB.

If the parameter is set to true then.

If the selection query is matched then it will update the values associated to it. If the selection query is not matched then it will insert a new document with the values.

Let’s understand this behavior

The school collection has the following documents

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4 },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

With upsert has a parameter set to true, the document provided in the query will be inserted.

try {
  db.restaurant.updateOne(
     { "name" : "Above and Beyond School" },
     { $set: {"_id" : 4, "violations" : 7, "New York" : "Manhattan" } },
     { upsert: true }
  );
} catch (e) {
  print(e);
}

If you have observed, the new document set that we have in the query didn’t match with the existing documents available in the database.

As the Upsert parameter is set to true so the document will be inserted as a new document within the database and the end result would be something like below:

Checkout MongoDB Tutorial

This would be the response

{
  "acknowledged" : true,
  "matchedCount" : 0,
  "modifiedCount" : 0,
  "upsertedId" : 4
}

And this is how the documents will look like:

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4 },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

{ "_id" : 4, "name" : "Above and Beyond School", "New York" : "Manhattan", "violations" : 7 }

So far we have understood how an update statement would work while updating one of the data elements within the document.

Frequently Asked MongoDB Interview Questions

Update Many Function:

Now let’s go through a process where multiple documents need to be updated. For this, we need to use the Update many functions within the Update statement.

db.collection.updateMany(
  ,
  ,
  {
    upsert: ,
    writeConcern: ,
    collation:
  }
)

Note: Code snippet referred from MongoDB official documentation

 Parameter Query Description
 Filter documentThis part describes the selection criteria of the  document that needs to be updated
 update document Whatever the documents needed to be updated,  this parameter will be the key and it will do the job
 upsert boolean If the upsert is set to true,
 If no documents are matched based on the query selection, a new document will be created.

 If the upsert is set to false, which is a default way
 Based on the query selection, if documents are matched then only the information will be updated.
 Write  concern document It is an optional parameter
 
collation
 document It is an optional parameter

Here is the set of documents that we have in the database, now let’s try out Update many function :

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4 },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

{ "_id" : 4, "name" : "Above and Beyond School", "New York" : "Manhattan", "violations" : 7 }

Based on the following operation, we set a filter saying update all violations which are greater than 4 flag for status:

try {
  db.restaurant.updateMany(
     { violations: { $gt: 3 } },
     { $set: { "Status" : true } }
  );
} catch (e) {
  print(e);
}

Based on the above filter criteria , we get to see this result as

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

And the updated documents will look like this:

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4, “Status” : true },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

{ "_id" : 4, "name" : "Above and Beyond School", "New York" : "Manhattan", "violations" : 7 , “Status” : true }

On contrary, if no matches were found, the operation would show a result in the following manner:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

Let’s go through one example where the upsert parameter is set to true:

try {
  db.schools.updateMany(
     { "Violations" : { $gt : 5 }, "name" : "International School" },
     { $set: { "Status" : false } },
     { upsert: true }
  );
} catch (e) {
  print(e);
}

Based on the above query, the response would be something like this:

{
  "acknowledged" : true,
  "matchedCount" : 0,
  "modifiedCount" : 0,
  "upsertedId" : ObjectId("56fd5dcb39ec682bdc609b03")
}

The final document after the update will look like below:

{ "_id" : 1, "name" : "International school", "New York" : "Manhattan", “violations”:4, “Status” : true },
{ "_id" : 2, "name" : "Jack the sparrow", "New York" : "Empire State", "violations" : 2 },
{ "_id" : 3, "name" : "Eternal Techno School", "New York" : "Brooklyn", "violations" : 0 }

{ "_id" : 4, "name" : "Above and Beyond School", "New York" : "Manhattan", "violations" : 7 , “Status” : true }
{ "_id" :ObjectId("56fd5dcb39ec682bdc609b03"), "name" : "International school", "New York" : "Manhattan", “violations”:5, “Status” : false },

As we didn’t have an exact document match, the above update many statements has inserted a new document in the database.

We hope that you have learned something today, so keep on practicing and make sure you learn something new every day and every time.

 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
MongoDB Training Apr 27 to May 12View Details
MongoDB Training Apr 30 to May 15View Details
MongoDB Training May 04 to May 19View Details
MongoDB Training May 07 to May 22View Details
Last updated: 03 Apr 2023
About Author

Prasanthi is an expert writer in MongoDB, and has written for various reputable online and print publications. At present, she is working for MindMajix, and writes content not only on MongoDB, but also on Sharepoint, Uipath, and AWS.

read more