

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

# \$1setIsSubset
<a name="setIsSubset"></a>

Amazon DocumentDB 中的`$setIsSubset`运算符用于确定一组值是否为另一组值的子集。它对于对数组字段执行基于集合的比较和操作很有用。

**参数**
+ `field`: 要应用`$setIsSubset`运算符的字段。
+ `set`：用于比较字段的集合。

## 示例（MongoDB 外壳）
<a name="setIsSubset-examples"></a>

以下示例演示如何使用`$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"] }
})
```

\$1注意：\$1 `$setIsSubset` 是一个聚合运算符，不能直接用于 find () 查询。在此示例中，`$expr`与一起使用`find()`来弥合查询运算符和聚合表达式之间的差距。

**输出**

```
[
  { "_id" : 1, "name" : "Product A", "tags" : [ "tag1", "tag2", "tag3" ] },
  { "_id" : 2, "name" : "Product B", "tags" : [ "tag1", "tag2" ] }
]
```

该查询返回该`tags`字段是集合子集的子集的文档`[&quot;tag1&quot;, &quot;tag2&quot;]`。

## 代码示例
<a name="setIsSubset-code"></a>

要查看使用该`$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()
```

------