Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$setIsSubset
Amazon DocumentDB 中的$setIsSubset运算符用于确定一组值是否为另一组值的子集。它对于对数组字段执行基于集合的比较和操作很有用。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$setIsSubset运算符来检查tags字段是否为指定集合的子集。
创建示例文档
db.products.insertMany([
{ _id: 1, name: "Product A", tags: ["tag1", "tag2", "tag3"] },
{ _id: 2, name: "Product B", tags: ["tag1", "tag2"] },
{ _id: 3, name: "Product C", tags: ["tag2", "tag3"] }
]);
查询示例
db.products.find({
$expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
})
*注意:* $setIsSubset 是一个聚合运算符,不能直接用于 find () 查询。在此示例中,$expr与一起使用find()来弥合查询运算符和聚合表达式之间的差距。
输出
[
{ "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
{ "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
该查询返回该tags字段是集合子集的子集的文档["tag1", "tag2"]。
代码示例
要查看使用该$setIsSubset命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
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('products');
const result = await collection.find({
$expr: { $setIsSubset: [["tag1", "tag2"], "$tags"] }
}).toArray();
console.log(result);
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')
db = client['test']
collection = db['products']
result = list(collection.find({
'$expr': {'$setIsSubset': [['tag1', 'tag2'], '$tags']}
}))
print(result)
client.close()
example()