

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1inc
<a name="inc"></a>

该`$inc`运算符用于将字段的值增加指定量。它用于更新数值字段，例如计数器或评级，而无需检索当前值、计算新值然后更新该字段。

**参数**
+ `field`：要递增的字段的名称。
+ `amount`：该字段的增量值。这可以是正值或负值。

## 示例（MongoDB 外壳）
<a name="inc-examples"></a>

以下示例演示如何使用`$inc`运算符来增加文档的`age`字段。

**创建示例文档**

```
db.users.insertOne({_id: 123, name: "John Doe", age: 30})
```

**查询示例**

```
db.users.updateOne({_id: 123}, {$inc: {age: 1}})
```

**查看更新的文档**

```
db.users.findOne({_id: 123})
```

**输出**

```
{ "_id" : 123, "name" : "John Doe", "age" : 31 }
```

## 代码示例
<a name="inc-code"></a>

要查看使用该`$inc`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function updateWithInc() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('users');

  const result = await collection.updateOne(
    { _id: 123 },
    { $inc: { age: 1 } }
  );

  console.log(result);

  await client.close();
}

updateWithInc();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def update_with_inc():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['users']

    result = collection.update_one(
        {'_id': 123},
        {'$inc': {'age': 1}}
    )

    print(result.modified_count)

    client.close()

update_with_inc()
```

------