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.
Syntax
{ $inc: { field1: amount1, field2: amount2, ... } }
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:
Key Takeaways About $inc Operator
- The $inc operator in MongoDB increments the value of a field by a specified amount.
- It can be used in embedded documents or arrays using dot notation.
- The $inc operator can be used in methods like update(), updateOne() according to requirements.
- Use of the $inc operator on a field with a null value will generate an error.
- It is an atomic operation within a single document.
Contact Us