View a markdown version of this page

$bitXor - Amazon DocumentDB

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

$bitXor

8.0.1 版中的新增内容。

Amazon DocumentDB 中的$bitXor运算符对整数值或长值执行按位异或运算。

参数

  • expressions: 由两个或更多表达式组成的数组,可以解析为整数或长整数。

示例(MongoDB Shell)

以下示例显示如何使用$bitXor运算符对两个字段执行按位异或。

创建示例文档

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()