参考 > 参考 > 经营者 > 更新运算符 > 现场更新操作员 > $ inc
在本页面
$inc
在$inc操作者通过增加指定的值的字段,并具有以下形式:
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
要<field>在嵌入式文档或数组中指定,请使用 点符号。
<field>
该$inc运营商接受正值和负值。
如果该字段不存在,请$inc创建该字段并将该字段设置为指定的值。
$inc在具有空值的字段上使用运算符将产生错误。
$inc 是单个文档中的原子操作。
考虑products包含以下文档的集合:
products
{ _id: 1, sku: "abc123", quantity: 10, metrics: { orders: 2, ratings: 3.5 } }
以下update()操作使用 $inc运算符将quantity字段减小2 (即增加-2),并将"metrics.orders"字段增大1:
update()
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 } }
也可以看看
db.collection.update(), db.collection.findAndModify()
db.collection.update()
db.collection.findAndModify()