MongoDB $inc Operator Example
In the following examples, we are working with:
Database: w3wiki
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs
Example 1: 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.
Query:
db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})
Output:
Example 2: 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.
Query:
db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})
Output:
Example 3: 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.
Query:
db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})
Output:
MongoDB – $inc Operator
MongoDB $inc or increment operator is a type of field update operator. $inc operator increases the values of the fields to the specified amount or increases the field by the given value.
Important Points
- This operator accepts positive and negative values.
- If the given field does not exist, then this operator will create a field and set the value of that field.
- This operator will generate an error, if you use this operator with a null value field.
- It is an atomic operation in a single document.
Contact Us