$inc
The $inc operator is used to increment the value of a field by a specified amount. It is used to update a numeric field, such as a counter or a rating, without having to retrieve the current value, calculate the new value, and then update the field.
Parameters
-
field: The name of the field to increment. -
amount: The amount by which to increment the field. This can be a positive or negative value.
Example (MongoDB Shell)
The following example demonstrates how to use the $inc operator to increment the age field of a document.
Create sample documents
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
Query example
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
View updated document
db.users.findOne({_id: 123})
Output
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
Code examples
To view a code example for using the $inc command, choose the tab for the language that you want to use: