

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

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

Amazon DocumentDB 中的`$bit`運算子可讓您對指定欄位的位元執行位元操作。這對於設定、清除或檢查數字中個別位元的狀態等任務很有用。

**參數**
+ `field`：要在其中執行位元操作的欄位。
+ `and`：用於對 欄位執行位元 AND 操作的整數值。
+ `or`：整數值，用於對 欄位執行位元 OR 操作。
+ `xor`：整數值，用於對 欄位執行位元 XOR 操作。

## 範例 (MongoDB Shell)
<a name="bit-examples"></a>

下列範例示範如何使用 `$bit`運算子對數值欄位執行位元操作。

**建立範例文件**

```
db.numbers.insert([
  { "_id": 1, "number": 5 },
  { "_id": 2, "number": 12 }
])
```

**查詢範例**

```
db.numbers.update(
  { "_id": 1 },
  { "$bit": { "number": { "and": 3 } } }
)
```

**輸出**

```
{
  "_id": 1,
  "number": 1
}
```

在此範例中，運算`$bit`子用於對 文件的「數字」欄位執行位元 AND 操作，其中 `_id`為 1。結果是 "number" 欄位的值設定為 1，這是原始值 5 與值 3 之間的位元 AND 操作的結果。

## 程式碼範例
<a name="bit-code"></a>

若要檢視使用 `$bit`命令的程式碼範例，請選擇您要使用的語言標籤：

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

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

async function main() {
  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('numbers');

  await collection.updateOne(
    { "_id": 1 },
    { "$bit": { "number": { "and": 3 } } }
  );

  const result = await collection.findOne({ "_id": 1 });
  console.log(result);

  await client.close();
}

main();
```

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

```
from pymongo import MongoClient

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['numbers']

collection.update_one(
    {"_id": 1},
    {"$bit": {"number": {"and": 3}}}
)

result = collection.find_one({"_id": 1})
print(result)

client.close()
```

------