$inc

在本页面

Definition

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

要在嵌入式文档或数组中指定<field>,请使用dot notation

Behavior

$inc运算符接受正值和负值。

如果该字段不存在,则$inc创建该字段并将该字段设置为指定的值。

在值为空的字段上使用$inc运算符将产生错误。

$inc是单个文档中的原子操作。

Example

考虑包含以下文档的集合products

{
  _id: 1,
  sku: "abc123",
  quantity: 10,
  metrics: {
    orders: 2,
    ratings: 3.5
  }
}

以下update()操作使用$inc运算符将quantity字段减少2(即,增加-2)并将"metrics.orders"字段增加1

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

更新后的文档类似于:

{
   "_id" : 1,
   "sku" : "abc123",
   "quantity" : 8,
   "metrics" : {
      "orders" : 3,
      "ratings" : 3.5
   }
}
首页