

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

`$inc` 運算子用於將欄位的值增加指定的數量。它用於更新數值欄位，例如計數器或評分，而無需擷取目前值、計算新值，然後更新欄位。

**參數**
+ `field`：要遞增的欄位名稱。
+ `amount`：要增加欄位的數量。這可以是正值或負值。

## 範例 (MongoDB Shell)
<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()
```

------