MongoDB Update Method (Day 9)

Before reading this article, I highly recommend reading the previous installments of the series:

The update method modifies the document(s) in a collection. Using the update method we can modify an entire document or a specific field of a document. The update method is similar to the update command in relational databases. It generally updates a single document at a time but we can update multiple documents using the “Multi” parameter. Finally, the update() method returns an object that contains the status of the operation.

Syntax: db.collection_Name.updat( { query , update , { upsert: <Boolean>, multi: <Boolean> } } )

Parameters

Parameter Type Description
Query Document Query is selection criteria for the update command.
Update Document Update criteria
Upsert Boolean Optional. By default set to False. If set to true, creates a new document when no document matches the query criteria otherwise doesn't insert a new document.
Multi Boolean Optional. By default set to False. If set to true, updates multiple documents that meet the query criteria otherwise updates a single document.

Behavior of Update Method

When we use an update command, then there are two possibilities:

  1. Update method modifies the specific fields.
  2. Update method replaces an existing document entirely.

Case 1: Update Specific Fields

If the <Update> parameter contains only an update operator such as: $set, $inc, $mul then the update() method updates only the corresponding fields in the document. If we want to modify an embedded document or an array as a whole then specify the replacement value for the field. To update a specific field of an embedded document or array use the dot (.) notation for the specific field.

Case 2: Replace the Entire Document

To replace an entire document the <Update> parameter contains only a field:value expression. In other words, <Update> parameters should not contain any update operator. We can't replace the _id field and the update method can't replace multiple documents.

When we execute an update method, MongoDB returns the following three values in the form of acknowledgment.

Name Type Description
nMatched Integer Returns the numbers of document that match the query
nUpserted Integer Returns the number of Upserted documents
nUpdated Integer Returns the number of Updated documents

First, we create a collection and insert some data into this collection.

Create Collection Command:

db.createCollection("Demo",{autoIndexID:true,size:5040321,max:100})

Insert Data

  1. {  
  2.     "_id": ObjectId("55c89859626ebe75ff8e8814"),  
  3.     "Title""MongoDB-Day1",  
  4.     "Likes": 3,  
  5.     "Author": {  
  6.         "PostBy""Pankaj",  
  7.         "Views": 2500  
  8.     },  
  9.     "Tags": ["MogoDB""SQL""Database"],  
  10.     "Rating": [{  
  11.         "By""Rahul",  
  12.         "Rate": 4  
  13.     }]  
  14. }  
  15.   
  16. {  
  17.     "_id": ObjectId("55c898a2626ebe75ff8e8815"),  
  18.     "Title""MongoDB-Day2",  
  19.     "Likes": 5,  
  20.     "Author": {  
  21.         "PostBy""Pankaj",  
  22.         "Views": 3500  
  23.     },  
  24.     "Tags": ["MogoDB""SQL""Database", "Introducti  
  25.  on"],  
  26.     "Rating": [{  
  27.         "By""Sandeep",  
  28.         "Rate": 4  
  29.     }, {  
  30.         "By""Rahul",  
  31.         "Rate": 5  
  32.     }]  
  33. }  
  34.   
  35. {  
  36.     "_id": ObjectId("55c898d1626ebe75ff8e8816"),  
  37.     "Title""MongoDB-Day3",  
  38.     "Likes": 4,  
  39.     "Author": {  
  40.         "PostBy""Pankaj",  
  41.         "Views": 4500  
  42.     },  
  43.     "Tags": ["MogoDB""Database""Introduction"],  
  44.     "Rating": [{  
  45.         "By""Sanjeev",  
  46.         "Rate": 3  
  47.     }, {  
  48.         "By""Div",  
  49.         "Rate": 5  
  50.     }]  
  51. }  
  52.   
  53. {  
  54.     "_id": ObjectId("55c898f1626ebe75ff8e8817"),  
  55.     "Title""MongoDB-Day4",  
  56.     "Likes": 9,  
  57.     "Author": {  
  58.         "PostBy""Pankaj",  
  59.         "Views": 6500  
  60.     },  
  61.     "Tags": ["MogoDB""Database"],  
  62.     "Rating": [{  
  63.         "  
  64.  By": "Sanjeev",  
  65.         "Rate": 5  
  66.     }]  
  67. }  
After inserting the preceding data, the Demo collection looks like the following:

Demo collection looks

Now we will execute some query and understand the behavior of the Update() method.

Update specific Fields

To update a specific field of a document use the update operators in the <update> parameter.

Query: db.Demo.update({Title:"MongoDB-Day1"},{$set:{Likes:10}})

This query updates the value of the Likes field of a document. That's the Title field containing the “MogoDB-Day1” value. This query updates the value of the first document that matches the query field.

Documents after Update

The value of the Likes field has been changed, as shown below:

Change value

In the preceding example, we use the “$set” update operator. The “$set” operator replaces the value of the field.

Let's see another update operator.

Query: db.Demo.update({Title:"MongoDB-Day1"},{$inc:{Likes:5}})

In this query, the “$inc” update operator increases the value of the Likes field by 5. In the following image, we can see that the value of the Likes field has been changed.

Documents after Update

The value of the Likes field is increased by 5.

field increased by 5

Update Embedded Document

To update a field of an embedded document, we can use dot (.) notation.

Query

db.Demo.update({Title:"MongoDB-Day1"},{$set:{"Author.PostBy":"Pankaj Choudhary","Author.Views ":6000}})

This query updates the “PostBy” and “Views” fields of the “Author” embedded document where the Title field of the document is equal to “MongoDB-Day1”.

Documents after Update

MongoDB

Important Point

When we create a collection with option parameters, then such collections are known as a capped collection. A Capped collection prohibits the updates that increase the document size that ensures that a document does not change its location on disk.

Let's see an example.

First, we create a “nam” capped collection.

example

We can see that the value of the capped parameter is “true”. In other words “nam” is a capped typed collection. Now we insert some data into the “nam” collection.

insert data

Let's try to update the document and see what will happen.

error

In the preceding query, we tried to update the “Name” field of the document, but MongoDB throws an error because we are trying to increase the size of the document. Here Sizeof(“Pankaj Kumar Choudhary”) > Sizeof(“Pankaj Kumar”).

Let's try another query.

query

The preceding query was executed successfully because this query doesn't increase the size of the document. Sizeof(“Pankaj”) > Sizeof(“pankaj Kumar”).

Conclusion

Capped collections have a property that Capped collections prohibit the updates that increase the document size. So if we are inserting a document into a Capped collection, then we should remember that in the future we can't increase the size of the document. Therefore, we should use a sufficient size of the document for further use.

Update Multiple Document

To update multiple documents, set the multi-option to true.

Query: db.Demo.update({"Author.PostBy":"Pankaj"},{$set:{Likes:13}},{multi:true})

This query sets the value of the “Likes” field equal to 13 where the value of the “Autore.Post” field is “Pankaj”.

Documents after Update

Update Documents

The preceding image shows that the value of Likes field has been changed.

Replace all Fields

If we pass a <update> document that contains only field and value pairs, in other words, we passed an <update> document without update operator, then the <update> document completely replaces the original document except for the _id field.

Query

db.Demo.update({Title:"MongoDB-Day1" },{Title:"Introduction to NoSQL",Author:"Nitin Yadav",Ta
gs:["NoSQL","MongoDB","SQL"]})


This query replaces the original document with the given document where the value of the “Title” field is “MongoDB-Day1”.

Documents after Update

Documents after Update

Use Upsert Method

If the Upsert option is set to true, then it creates a new document. When no document matches the query criteria, it won't insert a new document.

Query

db.Demo.update({Title:"MongoDB-Day5" },{Title:"MongoBD-Day6",Author:"Narendra Sharma",Tags:[" NoSQL","MongoDB","SQL"]},{upsert:true})

This query first matches the existing selection criteria. If any document matches the selection criteria then it will be replaced, otherwise insert a new document.

Documents after Update

A new document is created in the collection.

collection

Combine use of Upsert and Multi Options

In a combined use of the upsert and multi-option, there are two possibilities:
  1. If any document doesn't match the query pattern then a new document will be inserted.
  2. If any document(s) match the query pattern then it will update all those document(s).

Let's see an example for both cases.

Case 1: Document(s) match the query Pattern

Query

db.Demo.update({Title:"ASP.Net MVC5"},{$set:{"Likes" : 5, Author:{PostBy:"Sanjeev",Views:3200
},Tags:["ASP.Net","MVC"]}},{Multi:1,upsert:1})


Documents after Update

A new document has been inserted.

A new document

Case 2: When the document matches the query pattern

Query

db.Demo.update({"Author.PostBy":"Pankaj"},{$set:{"Likes" : 5, Author:{PostBy:"Sanjeev",Views:
3200},Tags:["ASP.Net","MVC"]}},{Multi:1,upsert:1})


Documents after Update

The existing document has been updated.

Documents Update

Update Embedded Document Array: To update a document of an embedded document array, use the index number of that document and the dot (.) notation.

Query

db.Demo.update({Title:"MongoDB-Day2"},{$set:{"Rating.1":{By:"Nivin",Rate:3}}})

This query updates the second embedded document of the “Rating” Array.

Document Before Update

Document

Document After Update

  1. {  
  2.      "_id" : ObjectId("55c898a2626ebe75ff8e8815"),  
  3.      "Title" : "MongoDB-Day2",  
  4.      "Likes" : 5,  
  5.      "Author" : {  
  6.              "PostBy" : "Sanjeev",  
  7.              "Views" : 3200  
  8.      },  
  9.      "Tags" : [  
  10.              "ASP.Net",  
  11.              "MVC"  
  12.      ],  
  13.      "Rating" : [  
  14.              {  
  15.                      "By" : "Sandeep",  
  16.                      "Rate" : 4  
  17.              },  
  18.              {  
  19.                      "By" : "Nivin",  
  20.                      "Rate" : 3  
  21.              }  
  22.      ]  
  23.  }  
This article described the update method and used it in various ways. In the next article, we will learn a new Collection Method.

Thanks for reading this article!
 
Author
Pankaj Kumar Choudhary
70 26.6k 13.4m
Next » MongoDB Remove Method (Day 10)