Increment field value on update in MongoDB using $inc

Increment field value on update in MongoDB using $inc

$inc

To increment a value in MongoDB we use the $inc operator. $inc increments the value of the field by the specified amount.

db.collection.update({query}, {$inc: {field: value}})

Example of $inc

Update all documents with a name equal to article and increment the field views by one. If the field does not exist mongodb sets its value to 0 before incrementing.

db.articles.updateMany({name: "article"}, {$inc: {views: 1}})

You can find more about update operators in the following link: Fields, Array and Modifiers update operators in MongoDB