Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$bitsAnySet
Amazon DocumentDB 中的$bitsAnySet运算符用于查询字段中指定位中至少有一个位设置为 1 的文档。此运算符允许您对存储在字段中的值执行按位运算,从而可以高效查询和分析具有按位特征的数据。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$bitsAnySet运算符查找flags字段中至少设置了一个位的文档。
创建示例文档
db.collection.insertMany([
{ _id: 1, flags: 0b1010 },
{ _id: 2, flags: 0b1100 },
{ _id: 3, flags: 0b0011 },
{ _id: 4, flags: 0b0100 }
]);
查询示例
db.collection.find({
flags: { $bitsAnySet: 0b1010 }
})
输出
{ "_id" : 1, "flags" : 10 }
{ "_id" : 2, "flags" : 12 }
{ "_id" : 3, "flags" : 3 }
该查询返回的文档中,该flags字段中至少设置了0b1010位掩码中指定的一个位。
代码示例
要查看使用该$bitsAnySet命令的代码示例,请选择要使用的语言的选项卡:
- 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('collection');
const result = await collection.find({
flags: { $bitsAnySet: 0b1010 }
}).toArray();
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['collection']
result = list(collection.find({
'flags': { '$bitsAnySet': 0b1010 }
}))
print(result)
client.close()