MongoDB Update Method
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:
| 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:
- Update method modifies the specific fields.
- Update method replaces an existing document entirely.
Case 1: Update Specific Fields
If the
1. Query: db.Demo.update({Title:”MongoDB-Day1″},{$set:{Likes:10}})
2. Query: db.Demo.update({Title:”MongoDB-Day1″},{$inc:{Likes:5}})
Update Embedded Document
3. Query : db.Demo.update({Title:”MongoDB-Day1″},{$set:{“Author.PostBy”:”Pankaj Choudhary”,”Author.Views “:6000}})
Update Multiple Document
4. Query: db.Demo.update({“Author.PostBy”:”Pankaj”},{$set:{Likes:13}},{multi:true})
Case 2: Replace the Entire Document
To replace an entire document the
Query
db.Demo.update({Title:”MongoDB-Day1″ },{Title:”Introduction to NoSQL”,Author:”Nitin Yadav”,Ta
gs:[“NoSQL”,”MongoDB”,”SQL”]})
Use Upsert Method
Query
db.Demo.update({Title:”MongoDB-Day5″ },{Title:”MongoBD-Day6″,Author:”Narendra Sharma”,Tags:[” NoSQL”,”MongoDB”,”SQL”]},{upsert:true})
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.
Query
db.Demo.update(
{Title:"ASP.Net MVC5"},
{
$set:{"Likes" : 5,
Author:{
PostBy:"Sanjeev",
Views:3200},
Tags:["ASP.Net","MVC"]
}
},
{Multi:1,upsert:1}
)
2. If any document(s) match the query pattern then it will update all those document(s).
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}
)
3.Update Embedded Document Array: To update a document of an embedded document array, use the index number of that document and the dot (.) notation.
Example 1 :
{
"Title": "MongoDB-Day4",
"Likes": 9,
"Author": {
"PostBy": "Pankaj",
"Views": 6500
},
"Tags": ["MogoDB", "Database"],
"Rating": [{
"By": "Sanjeev",
"Rate": 5
}]
}
db.Demo.update(
{Title:"MongoDB-Day2"},
{$set:
{
"Rating.1":{
By:"Nivin",
Rate:3
}
}
})
Create Collection Command:
db.createCollection(“Demo”,{autoIndexID:true,size:5040321,max:100})

Insert Document
db.shoppingCart.insertMany(
[
{index: NumberInt(1)},{index: NumberInt(2)},
{index: NumberInt(3)},{index: NumberInt(4)},
{index: NumberInt(5)}
]
)

1.$set Operator

$set Example –
db.shoppingCart.update(
//query
{index: 2},
//update
{$set: {
cartId: NumberInt(325),
customer: {
name: "Mike Foster",
email: "mfoster@gmail.com",
age: NumberInt(27)
},
cart:[]
}
},
//update Options
{}
)
2.$unSet Operator

fieldValue can be any integers or empty string.
//1. Remove field :
db.shoppingCart.update(
//query
{index: 1},
//update
{$unset: {
cartId: 1,
cart:""
}
},
//update Options
{}
)
//2.Remove from child document field :
db.shoppingCart.update(
//query
{index: 2},
//update
{$unset: {
"customer.name":1,
"customer.age":1
}
},
//update Options
{}
)
//3.Remove Child document :
db.shoppingCart.update(
//query
{index: 2},
//update
{$unset: {
customer: 1
}
},
//update Options
{}
)
By default update method found first document, if we did not provide the find query (find({}))
db.shoppingCart.update(
//query
{},
//update
{$unset: {
customer: 1
}
},
//update Options
{}
)
3. Update – one Document

If any changes in the field value , it can only be modified. Else modification will not happen , we can verify in the result count.
db.shoppingCart.update(
{}, //query
{ //update
$set: {processed: false}
}
)
//
db.shoppingCart.update(
{index: 1},
{
$set: {processed: false}
}
)
3. Update – Many Document

db.shoppingCart.update(
{},
{
$set: {processed: false}
},
{multi: true}
)
4. updateOne – One Document

db.shoppingCart.updateOne(
{cartId: 325},
{
$set: {processed: true}
},
{}
)
5. updateMany – Many Document

db.shoppingCart.updateMany(
{cart: {$exists: false}},
{
$set: {cart: []}
},
{}
)
6. replaceOne – replace one Document

db.shoppingCart.replaceOne(
{"index":1},
//replacement Object
{
"index": NumberInt(1),
"processed": false,
"cart": ["item1", "item2"]
},
{}
)
7. Combine multiple update operators

db.shoppingCart.updateOne(
{"index":4},
//replacement Object
{
$set: {
cartId: NumberInt(435),
"customer.name":"Samanta Larsen",
"customer.email":"slarsent@tgs.com"
},
$unset: { newOrder: 1}
},
{}
)
8. $rename

db.shoppingCart.updateMany(
{cartId: {$exists: true}},
//replacement Object
{
$rename: {
cartId: "orderId"
}
},
{}
)
9. $currentDate

//Using $set Operator
db.shoppingCart.updateOne(
{index: 1},
//replacement Object
{
$set: {
updatedAt: new Date()
}
},
{}
)
//Using $currentDate
db.shoppingCart.updateMany(
{updatedAt: {$exists: false}},
//replacement Object
{
$currentDate: {
updatedAt: true
}
},
{}
)
//Add Field and update date
db.shoppingCart.updateMany(
{orderId: 325},
//replacement Object
{
$set: {
cart: ["item1"]
},
$currentDate: {
updatedAt: true
}
},
{}
)