$inc

Definition

  • $inc
  • The $inc operator increments a field by a specified value andhas the following form:
  1. { $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

To specify a <field> in an embedded document or in an array, usedot notation.

Behavior

The $inc operator accepts positive and negative values.

If the field does not exist, $inc creates the field and setsthe field to the specified value.

Use of the $inc operator on a field with a null value willgenerate an error.

$inc is an atomic operation within a single document.

Example

Consider a collection products with the following document:

  1. {
  2. _id: 1,
  3. sku: "abc123",
  4. quantity: 10,
  5. metrics: {
  6. orders: 2,
  7. ratings: 3.5
  8. }
  9. }

The following update() operation uses the$inc operator to decrease the quantity field by 2(i.e. increase by -2) and increase the "metrics.orders" fieldby 1:

  1. db.products.update(
  2. { sku: "abc123" },
  3. { $inc: { quantity: -2, "metrics.orders": 1 } }
  4. )

The updated document would resemble:

  1. {
  2. "_id" : 1,
  3. "sku" : "abc123",
  4. "quantity" : 8,
  5. "metrics" : {
  6. "orders" : 3,
  7. "ratings" : 3.5
  8. }
  9. }

See also

db.collection.update(),db.collection.findAndModify()