Before reading this article, I highly recommend reading the following previous parts 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. The update method generally updates a single document at a time but we can update multiple documents using the “Multi” parameter. 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 the following two possibilities:
- Update method modifies the specific fields.
- 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 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 a update method, MongoDB returns the following three values in the form of acknowledgement.
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
- {
- "_id": ObjectId("55c89859626ebe75ff8e8814"),
- "Title": "MongoDB-Day1",
- "Likes": 3,
- "Author": {
- "PostBy": "Pankaj",
- "Views": 2500
- },
- "Tags": ["MogoDB", "SQL", "Database"],
- "Rating": [{
- "By": "Rahul",
- "Rate": 4
- }]
- }
-
- {
- "_id": ObjectId("55c898a2626ebe75ff8e8815"),
- "Title": "MongoDB-Day2",
- "Likes": 5,
- "Author": {
- "PostBy": "Pankaj",
- "Views": 3500
- },
- "Tags": ["MogoDB", "SQL", "Database", "Introducti
- on"],
- "Rating": [{
- "By": "Sandeep",
- "Rate": 4
- }, {
- "By": "Rahul",
- "Rate": 5
- }]
- }
-
- {
- "_id": ObjectId("55c898d1626ebe75ff8e8816"),
- "Title": "MongoDB-Day3",
- "Likes": 4,
- "Author": {
- "PostBy": "Pankaj",
- "Views": 4500
- },
- "Tags": ["MogoDB", "Database", "Introduction"],
- "Rating": [{
- "By": "Sanjeev",
- "Rate": 3
- }, {
- "By": "Div",
- "Rate": 5
- }]
- }
-
- {
- "_id": ObjectId("55c898f1626ebe75ff8e8817"),
- "Title": "MongoDB-Day4",
- "Likes": 9,
- "Author": {
- "PostBy": "Pankaj",
- "Views": 6500
- },
- "Tags": ["MogoDB", "Database"],
- "Rating": [{
- "
- By": "Sanjeev",
- "Rate": 5
- }]
- }
After inserting the preceding data, the Demo collection looks as in the following:
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 in the following:
In the preceding example we use the “$set” update operator. The “$set” operator replaces the value of the field.
Let us 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.
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 UpdateImportant 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.
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.
Let us try to update the document and see what will be happen.
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.
The preceding query was executed successfully because this query doesn't increase the size of 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. So 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 UpdateThe preceding image shows that the value of the
Likes field has been changed.
Replace all Fields
If we pass an <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 UpdateUse Upsert Method
If the Upsert option is set to true then it creates a new document when no document matches the query criteria otherwise 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.
Combine use of Upsert and Multi Options
In a combined use of the upsert and multi option there are two possibilities:
- If any document doesn't match the query pattern then a new document will be insert.
- If any document(s) match the query pattern then it will update all those document(s).
Let's see an example for both the 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.
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.
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 After Update
- {
- "_id" : ObjectId("55c898a2626ebe75ff8e8815"),
- "Title" : "MongoDB-Day2",
- "Likes" : 5,
- "Author" : {
- "PostBy" : "Sanjeev",
- "Views" : 3200
- },
- "Tags" : [
- "ASP.Net",
- "MVC"
- ],
- "Rating" : [
- {
- "By" : "Sandeep",
- "Rate" : 4
- },
- {
- "By" : "Nivin",
- "Rate" : 3
- }
- ]
- }
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 the article.