MongoDB Update Query
The MongoDb update() method is used to update or modify the existing document in a collection. All update statements requires at least two arguments.
Syntax of Update Document
db.collection.update(filter, update, options)
Here, the filter is the selection criteria for updating the data, update is the data on which the update applies and the third parameter is the options which is an optional field. The options can be upsert, multi, collation, arrayFilters etc.
Update Operators
These are the update operators used in update document.
Name | Description |
$addToSet | It adds a value to the list and ensures that no duplicate items added to the set. |
$currentDate | to set the value of a field to current date. |
$inc | increments the value of a field with the mentioned value. |
$min | It updates the field, only when the given value is less than the existing field value. |
$max | It updates the field, only when the given value is greater than the existing field value. |
$mul | It multiplies the value of the field by the given amount. |
$rename | It is used to rename the field. |
$set | It sets or updates the value of a field. |
$unset | It removed the given field from the document. |
Types of Update
- update()
- updateOne()
- updateMany()
update() method
It updates the value in the existing document of a collection based on the specified criteria.
Syntax
db.collection.update(filter, update, options)
Example
Suppose, the user 'Andy Joya' decides to update her age and class. The following statement can do this -
> db.students.update({name: "Andy Joya"},{$set: {age: 11, class: '5B'}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In MongoDb, only one document is updated by default, either single or first matching document only. To update multiple documents, we need to set a third parameter 'multi:true'.
> db.students.update({class: '5B'},{$set: {age: 11}},{multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 0 })
updateOne() method
It updates the first matching document in a collection based on the specified criteria.
Syntax
db.collection.updateOne(filter, update, options)
Example
> db.students.updateOne({name: "Rana Soi"},{$set: {age: 12}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
updateMany() method
It updates multiple documents in a collection based on the specified criteria.
Syntax
db.collection.updateMany(filter, update, options)
Example
> db.students.updateMany({age: 11},{$set: {class: '5C'}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
MongoDb update addtoset
MongoDb $addtoset appends a value to the existing value and ensures that no duplicate items added to the set.
Consider a document in a collection 'profit' containing an array field months:
{ "_id" : ObjectId("5d47a06e874addff7e25865c"), "months" : [ "Jan", "Mar" ] }
The following operation appends the array ["June", "Aug"] to the months field.
> db.profit.update(
{_id: ObjectId("5d47a06e874addff7e25865c")},
{$addToSet: {"months": ["Jun","Aug"]}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.profit.find().pretty();
{
"_id" : ObjectId("5d47a06e874addff7e25865c"),
"months" : [
"Jan",
"Mar",
[
"Jun",
"Aug"
]
]
}
MongoDb update inc
The MongoDb $inc operator increments or decrements a field value by the given value.
Syntax
{ $inc: {<field>: <amount>}}
Consider a document in a collection 'sales':
{ "_id" : ObjectId("5d47e5196d3e953fcb82a759"), "Item" : 101, "Sales" : 50 }
{ "_id" : ObjectId("5d47e5366d3e953fcb82a75a"), "Item" : 102, "Sales" : 70 }
The following update() uses the $inc operator to increase the sales quantity of item1 by 10.
> db.sales.update(
... {Item: 101},
... {$inc: {Sales: 10}}
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sales.find();
{ "_id" : ObjectId("5d47e5196d3e953fcb82a759"), "Item" : 101, "Sales" : 60 }
{ "_id" : ObjectId("5d47e5366d3e953fcb82a75a"), "Item" : 102, "Sales" : 70 }
MongoDb update min
The $min is used to update the minimum value. If the specified min value is less than the existing field value, then it is updated with the specified value otherwise it does not update the existing value. Basically, it compares the specified and existing field value and updates with lower value.
Consider a document in a collection 'lowscore':
{ "_id" : ObjectId("5d48143b4194133ee2a1e567"), "sub" : "CHM", "score" : 60 }
The following operation compares the current score value with specified value and updates-
> db.lowscore.update({sub:"CHM"},{$min: {score: 50} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.lowscore.find();
{ "_id" : ObjectId("5d48143b4194133ee2a1e567"), "sub" : "CHM", "score" : 50 }
MongoDb update max
The $max is used to update the maximum value. If the specified max value is greater than the existing field value, then it updates with the specified value otherwise it does not update the existing value. Basically, it compares the specified and existing field value and updates with greater value.
Consider a document in a collection 'topscore':
{ "_id" : ObjectId("5d4813234194133ee2a1e566"), "sub" : "PHY", "score" : 88 }
The following operation compares the current score value with specified value and updates-
> db.topscore.update({sub:"PHY"},{$max: {score: 90} });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.topscore.find();
{ "_id" : ObjectId("5d4813234194133ee2a1e566"), "sub" : "PHY", "score" : 90 }
MongoDb update rename
The MongoDb $rename operator is used to update the name of a document field.
Syntax of $rename
{$rename: {<field>: <value>}}
Example
Here, we have renamed the 'Item' and 'Sales' field values to 'Product' and 'Marketing'-
> db.sales.update({'Item': 101},{$rename: {'Item':'Product', 'Sales':'marketing'}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
MongoDb update unset
The MongoDb $unset operator is used to delete a particular field.
Syntax of $unset
{$unset: {<field>: ""}}
Example
Here is the operation to delete the 'Product' field from the 'sales' collection.
> db.sales.update({'Item':102},{$unset: {'Sales': ""}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sales.find();
{ "_id" : ObjectId("5d47e5196d3e953fcb82a759"), "Sales" : 60, "Product" : 101 }
{ "_id" : ObjectId("5d47e5366d3e953fcb82a75a"), "Item" : 102 }