- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $inc
$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:The following example increments the value of
quantity
by5
for the first matching document in theproducts
collection wheresku
equalsabc123
:To update all matching documents in the collection, specify
multi:true
option in theupdate()
method. For example:The
update()
operation increments the value of theage
field by1
for all documents in therecords
collection that have anage
field equal to20
.The
$inc
operator can operate on multiple fields in a document. The followingupdate()
operation uses the$inc
operator to modify both thequantity
field and thesales
field for the first matching document in theproducts
collection wheresku
equalsabc123
:In the above example, the
$inc
operator expression specifies-2
for thequantity
field to decrease the value of thequantity
field (i.e. increment by-2
) and specifies2
for thesales
field to increase the value of thesales
field by2
.