Navigation
This version of the documentation is archived and no longer supported.

$inc

$inc

The $inc operator increments a value of a field by a specified amount. If the field does not exist, $inc adds the field and sets the field to the specified amount. $inc accepts positive and negative incremental amounts. Consider the following syntax:

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

The following example increments the value of quantity by 5 for the first matching document in the products collection where sku equals abc123:

db.products.update( { sku: "abc123" },
                    { $inc: { quantity: 5 } } )

To update all matching documents in the collection, specify multi:true option in the update() method. For example:

db.records.update( { age: 20 }, { $inc: { age: 1 } }, { multi: true } );

The update() operation increments the value of the age field by 1 for all documents in the records collection that have an age field equal to 20.

The $inc operator can operate on multiple fields in a document. The following update() operation uses the $inc operator to modify both the quantity field and the sales field for the first matching document in the products collection where sku equals abc123:

db.products.update( { sku: "abc123" },
                    { $inc: { quantity: -2, sales: 2 } } )

In the above example, the $inc operator expression specifies -2 for the quantity field to decrease the value of the quantity field (i.e. increment by -2) and specifies 2 for the sales field to increase the value of the sales field by 2.