Introduction to MongoDB $inc Operator

MongoDB is a document-oriented database that provides many powerful operators for updating documents. The $inc operator allows us to perform atomic increment operations on specified fields. This operator can be applied to numeric fields, such as integers and floats.

Syntax

The $inc operator uses the following syntax:

{ $inc: { <field1>: <amount1>, ... } }

Where <field> is the name of the field to be incremented and <amount> is the value to be added or subtracted.

Use cases

The $inc operator can be used to conveniently perform atomic increment operations on fields of a document. This is particularly useful when dealing with fields that need to be accumulated or counted. For example, we can use $inc to count the number of times a user logs in.

Examples

Example 1

Suppose we have a collection named users that contains the following documents:

{ "_id": 1, "username": "Alice", "login_count": 3 }
{ "_id": 2, "username": "Bob", "login_count": 5 }
{ "_id": 3, "username": "Charlie", "login_count": 2 }

Now suppose we want to increment the login_count field of Alice by 2. We can use the following code:

db.users.updateOne({ username: "Alice" }, { $inc: { login_count: 2 } })

After running the above code, the login_count field of Alice will be updated from 3 to 5.

Example 2

Suppose we have a collection named users that stores information about each user, including their name and points. We want to increment the points of a particular user. We can use the $inc operator to achieve this.

Suppose we want to increment the points of the user named Alice by 10:

db.users.updateOne({ name: "Alice" }, { $inc: { points: 10 } })

After running the above command, if Alice had 20 points before, she will now have 30 points.

Note that if the points field does not exist in the original document, the $inc operator will automatically create the field and set its value to the specified increment value. Additionally, negative values can be used to achieve decrement operations.

Conclusion

The $inc operator is a very convenient operator that can be used for atomic increment operations. It makes it easy for us to count or accumulate fields of a document. It is important to note that $inc can only be applied to numeric fields, or else it will result in an error.