本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$bitAnd
8.0.1 版的新功能。
Amazon DocumentDB 中的$bitAnd運算子會對整數或長值執行位元 AND 操作。
參數
範例 (MongoDB Shell)
下列範例顯示如何使用 $bitAnd 運算子對兩個欄位執行位元 AND。
建立範例文件
db.flags.insertMany([
{_id: 1, a: 13, b: 10},
{_id: 2, a: 7, b: 5},
{_id: 3, a: 15, b: 9}
]);
查詢範例
db.flags.aggregate([
{ $project: { result: { $bitAnd: ["$a", "$b"] } } }
]);
輸出
[
{_id: 1, result: 8},
{_id: 2, result: 5},
{_id: 3, result: 9}
]
在二進位中:13 (1101) 和 10 (1010) = 8 (1000);7 (0111) 和 5 (0101) = 5 (0101);15 (1111) 和 9 (1001) = 9 (1001)。
程式碼範例
若要檢視使用 $bitAnd 運算子的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('flags');
const result = await collection.aggregate([
{ $project: { result: { $bitAnd: ["$a", "$b"] } } }
]).toArray();
console.log(result);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
def example():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
try:
db = client['test']
collection = db['flags']
result = list(collection.aggregate([
{'$project': {'result': {'$bitAnd': ['$a', '$b']}}}
]))
print(result)
finally:
client.close()
example()