对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$inc(更新操作符)

$inc

The $inc operator increments a field by a specified value.

可以使用 $inc 查找托管在以下环境中的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

The $inc operator has the following form:

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

要在嵌入式文档或数组中指定 <field>,请使用点符号。

从 MongoDB 5.0 开始,更新操作符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。详情请参阅更新操作符行为

The $inc operator accepts positive and negative values.

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

Using the $inc operator on a field with a null value generates an error.

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

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $inc with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).

创建 products 集合:

db.products.insertOne(
{
_id: 1,
sku: "abc123",
quantity: 10,
metrics: { orders: 2, ratings: 3.5 }
}
)

The following updateOne() operation uses the $inc operator to:

  • "metrics.orders" 字段增加 1

  • quantity 字段减少 2(减少 quantity)。

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

操作返回以下结果:

{
_id: 1,
sku: 'abc123',
quantity: 8,
metrics: { orders: 3, ratings: 3.5 }
}
给本页内容打分