Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$bitsAllSet
Amazon DocumentDB 中的$bitsAllSet运算符用于查询字段中特定位集全部设置为 1 的文档。此运算符允许您对字段值执行按位运算,并且在需要检查数值中各个位的状态时非常有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$bitsAllSet运算符来查找该flags字段设置了由位掩码指定的所有位的文档。
创建示例文档
db.collection.insert([
{ _id: 1, flags: 0b1010 },
{ _id: 2, flags: 0b1100 },
{ _id: 3, flags: 0b1110 }
])
查询示例
db.collection.find({ flags: { $bitsAllSet: 0b1100 } })
输出
{ "_id": 2, "flags": 12 },
{ "_id": 3, "flags": 14 }
在此示例中,查询会检查flags字段中是否包含由位掩码0b1100(表示十进制值 12)指定的所有位的文档。带有 _id 2 和 3 的文档符合此标准,因为它们的flags字段值设置了所有必需的位(第 3 和第 4 个最低有效位)。
代码示例
要查看使用该$bitsAllSet命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findWithBitsAllSet() {
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('collection');
const result = await collection.find({ flags: { $bitsAllSet: 0b1100 } }).toArray();
console.log(result);
await client.close();
}
findWithBitsAllSet();
- Python
-
from pymongo import MongoClient
def find_with_bits_all_set():
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.collection
result = list(collection.find({ 'flags': { '$bitsAllSet': 0b1100 } }))
print(result)
client.close()
find_with_bits_all_set()