Blog

MongoDB Update Document

In today’s article we will be focusing 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

With the use of 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 later part in this article.

Accelerate Your career with MongoDB Training and become expertise in MongoDB. Enroll For Free MongoDB Training Demo!

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 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

Mongodb Update One:

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

Checkout MongoDB Interview Questions

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 }

This 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 behaviour

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 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 element within the document.

Frequently Asked MongoDB Interview Questions & Answers

Update Many Function:

Now let’s go through a process where multiple documents needs to be updated. For this we need to use Updatemany function within Update statement.

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

Note: Code snippet referred from MongoDB official documentation

 Parameter  Query  Description
 Filter  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.
 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:

{ "_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 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 statement has inserted a new document in the database.

Explore MongoDB Sample Resumes! Download & Edit, Get Noticed by  Employers!Download Now!

We hope that you have learnt something today, so keep on practising and make sure you learn something new everyday and every time.


RELATED COURSES

Get Updates on Tech posts, Interview & Certification questions and training schedules

Resolve the captcha 6 + 8 =