Tuesday 26 July 2016

UPDATE operations in MongoDB

In our last post we saw how to create documents in MongoDB and how to get the data back (i.e READ) from MongoDB. In this, we are going to how to UPDATE document/documents inside MongoDB.

Let's get started..

Before going to see different types of update operations in MongoDB, now let's have a look at the structure of the basic update command in MongoDB.

      db.numbers.updateOne({select}, {update}, {upsert})


  • Select : option is used to select the particular document which you want to update.
  • update : actual update command goes here.
  • upsert : This is optional in MongoDB. If MongoDB didn't find any document in select criteria, then we can insert that UPDATE operation into MongoDB with this option. Don't worry, let's see all these in detail.

MongoDB provides full flexibility across all collections i.e. If you want to add a new filed (column in Relational world) to the particular document, you actually need not to ALTER the collection structure(Table in SQL) like in SQL. We can use simple UPDATE command to add a new field to the document. This is what we called as "Flexible Schema".

MongoDB provides three types of update operations.

  1. updateOne
  2. updateMany
  3. replaceOne
Let's see one example for each.

updateOne : 

This command is used to update single document in MongoDB collection. Below is the example for the same.

Let's consider that we have one collection called "foo" and you want to set c : 10 where a : 9

First let's see the structure of the "foo" collection using "findOne" operation.


See that the collection "foo" has 4 documents inside that. Now, let's find the document where a : 9. To do that we have to use "find" operator.


But, this document does has the filed "c". Now, let's update this document.


See, here we have used $set operator to set the value of c as 10, where a : 9. Below are the some of the filed update operators in MongoDB. Just have a look.

Field update operators : 

  • $inc : Increments the value of the field by the specified amount
  • $mul : Multiplies the value of the field by the specified amount.
  • $rename : Renames a field.
  • $setOnInsert : Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
  • $set : Sets the value of a field in a document.
  • $unset : Removes the specified field from a document.
  • $min : Only updates the field if the specified value is less than the existing field value.
  • $max : Only updates the field if the specified value is greater than the existing field value.
  • $currentDate : Sets the value of a field to current date, either as a Date or a Timestamp.
Let's see one example for each.

$inc : 

As we know that, it is used to increment the value by specified amount of times. There is no "$dec" operator in MongoDB. We can use the same "$inc" to decrements the value. Let's see how we can do that.

Below update command increments the value of filed "a" by 2.

Before update:


After update :


see, after update the update operation the value of "a" is incremented by one.

Now, let's see how we can use the same operator to decrement the value.


Wow, we have decremented the value "a" by 5, with the same "$inc" operator. In this way we can use the "$inc" to decrement the value also.

$mul : 

This is very straight forward command, used to multiply the value of the field by specified amount of times.

Have look at the below example. Here, we are multiplying the value of field "a" by 2.

Before going to do update operation, let's check the value of "a" where c is 10.

Now, multiply the value of the "a" by 2 using $mul operator.


$rename : 

If you want rename any of the fields in MongoDB doccument, we can use this operator.

Let's try to rename field "a" to "aa".

Before rename:




After rename :


$setOnInsert : 

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing. Let's see the example now.

A collection named "sample" doesn't has any documents inside it. Now, we are gonna insert one document into it using $setOnInsert operator.



Query :

db.sample.updateOne({_id:1}, {$set:{item:"apple"}, $setOnInsert:{defaultQty:10}},

                                     {upsert:true})




$set : 

Till now, we have used this operator so many times in our tutorial. Any how lemme explain it again.
"$set" operator is used to set the value of the filed. Let's see an example now. Here we are going to set the value of the field "a" to 5 where c:3




$unset :

This operator is used to removed the specified field from document. Now, let's try to remove the field "a" from the document where c:6





See, the field "a" has been removed from the document.




$min  and $max :

"$min" operator is used to update the value of the field if the specified value is less than the existing field.
Similarly, $max operator is used to update the value of the field if the specified value is greater than the existing field.

Let's see one example for each.



Now, we are going to update the field "a" to 10 where b:8 using $min operator.

See, it didn't update anything, as the specified value is (a:10)  not less than the existing value. i.e a:7

similarly, you can try "$max" operator.

$currentDate :

$currentDate operator works similar to the GETDATE() in SQL world. It is simply used to get the current time stamp. Let's see one simple example now.



Update array fields :


  • $push : Adds an item to an array
  • $pushAll : Adds several items to an array (Deprecated)
  • $pull : Removes all array elements that match a specified query
  • $pullAll : Removes all matching values from an array
  • $pop : Removes the first or last element of an array
  • $addToSet : Adds an element to the array if the array doesn't has that element already

Now, let's do some exercises on these array operators.

Consider, we have a collection called "likes" which is having only one document with 3 fields.



Now, let's insert "Swimming" into likes array using "$push" operator.


Awesome !!, its updated. Now, let's remove (pull) Cricket from likes array using "$pull" operator.


It's done. In the same way, we can use "$pushAll" and "$pullAll" operators to push/pull multiple elements into/from an array. Below one is the example for "$pullAll" operator.


Did you notice anything new in the above updateOne query. Here we have used an array. If you have more than one value to be removed/updated, please make sure that you have used an array ([]) to represent those values.

Another important operator is "$addToSet" operator. This is also used to insert the element into an array. It works similar to the "$push", but the main difference is "$push" allows duplicates to be added to an array, where as "$addToSet" operator doesn't allow duplicates. What does it mean?..Let's see one example now.

First check the likes collection using find() query.


The likes array consists of only 2 values. i.e. Wrestling and Swimming. Now, let's try to insert "Swimming" again into likes array using "$push" operator.


See, its inserted "Swimming" into likes array, which means that "$push" operator allowing duplicates. Now, try the same thing with "$addToSet" operator. 


Awesome, it hasn't inserted any element into likes array.

$position : 

$position operator is used to insert the array element at particular position.

Please google for $each, $slice operators.

UpdateMany : 

As its name suggests, updateMany command is used to update many documents inside one collection.




ReplaceOne :

This command is very important. It is used to replace the entire document with another.



Note : We don't have replaceMany command in MongoDB.



Next post : Delete in MongoDB










5 comments:

  1. It’s a wonderful blog you shared here, I read the whole content and found it so easy to understand in language and is also full of amazing and useful information. Thanks a lot for sharing it.
    Hire Mongodb developer

    ReplyDelete
  2. Very good blog! For sharing content and such nice information for me. I hope you will share some more content about. Please keep sharing! Hire Mongo DB Developer

    ReplyDelete