Open In App
Related Articles

MongoDB – Increment Operator ( $inc )

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value. You can also use this operator in embedded/nested documents. You can use this operator in methods like update(), updateOne() etc. according to your requirements.
  • This operator accepts positive and negative values.
  • If the given field does not exist, then this operator will create field and set the value of that field.
  • This operator will generate an error, if you use this operator with null value field.
  • It is an atomic operation in a single document.
Syntax:
{ $inc: { field1: amount1, field2: amount2, ... } }
In the following examples, we are working with:
Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs.

Increment the value of the field using $inc operator:

In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100.
db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})

                    

Increment the value of the field in the array using $inc operator:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10.
db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})

                    

Increment the value of the field in embedded document using $inc operator:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2.
db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})

                    


Last Updated : 19 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads