MongoDB $inc

MongoDB has an $inc field update operator that allows you to increment a value by a specific amount.

You can use positive and negative values (i.e. to increment or decrement the value).

If the field doesn’t already exist, it is created with the specified value.

Example

Suppose we have a collection called dogs with the following document:

{ "_id" : 1, "name" : "Wag", "weight" : 10 }

Here, the weight field contains a value that can be incremented or decremented.

Increment

We can use the $inc operator in conjunction with the update() method to increment this dog’s weight.

Like this:

db.dogs.update(
  { _id: 1 },
  { $inc: { weight: 5 } }
)

Output:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

This tells us that one document was matched and modified.

Let’s check the collection again:

db.dogs.find()

Result:

{ "_id" : 1, "name" : "Wag", "weight" : 15 }

We can see that the dog’s weight has incremented by 5.

Decrement

You can decrement the value by providing a negative value to the $inc operator.

Like this:

db.dogs.update(
  { _id: 1 },
  { $inc: { weight: -5 } }
)

Output:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Check the collection:

db.dogs.find()

Result:

{ "_id" : 1, "name" : "Wag", "weight" : 10 }

We can see that the weight has now been decremented by 5.

Increment a Field that Doesn’t Exist

When you increment a field that doesn’t exist in the document, the field is added and assigned the specified value.

Example:

db.dogs.update(
  { _id: 1 },
  { $inc: { weight: 1, height: 30 } }
)

Output:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Notice that we updated two fields; the weight field and the height field (which didn’t originally exist).

Let’s check the document again:

db.dogs.find()

Result:

{ "_id" : 1, "name" : "Wag", "weight" : 11, "height" : 30 }

We can see that the weight field has been incremented by 1, and a new height field has been added with the specified value of 30.