View a markdown version of this page

$bitXor - Amazon DocumentDB

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

$bitXor

8.0.1 版的新功能。

Amazon DocumentDB 中的$bitXor運算子會對整數或長值執行位元 XOR 操作。

參數

  • expressions:兩個或多個表達式的陣列,可解析為整數或長。

範例 (MongoDB Shell)

下列範例顯示如何使用 $bitXor 運算子對兩個欄位執行位元 XOR。

建立範例文件

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: { $bitXor: ["$a", "$b"] } } } ]);

輸出

[ {_id: 1, result: 7}, {_id: 2, result: 2}, {_id: 3, result: 6} ]

在二進位中:13 (1101) XOR 10 (1010) = 7 (0111);7 (0111) XOR 5 (0101) = 2 (0010);15 (1111) XOR 9 (1001) = 6 (0110)。

程式碼範例

若要檢視使用 $bitXor 運算子的程式碼範例,請選擇您要使用的語言標籤:

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: { $bitXor: ["$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': {'$bitXor': ['$a', '$b']}}} ])) print(result) finally: client.close() example()