

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

# $sampleRate
<a name="sampleRate"></a>

8.0.1 版中的新增内容。

弹性集群不支持。

Amazon DocumentDB 中的`$sampleRate`运算符根据指定速率对输入文档的随机样本进行匹配。您可以在`find()`查询筛选器或聚合`$match`阶段使用它。由于选择是概率性的，因此返回的文档数量是近似值，并且可能因运行而异。

**参数**
+ `value`：范围内`[0, 1]`（含）的数字，直接传递给运算符（例如，`{ $sampleRate: 0.3 }`），用于设置包括每个文档的概率。值为不`0`返回任何文档；值为`1`返回所有文档。

## 示例（MongoDB Shell）
<a name="sampleRate-examples"></a>

以下示例使用`$sampleRate`返回集合中大约 30% 的文档。

**创建示例文档 **

```
db.events.insertMany([
  { _id: 1, type: "click" },
  { _id: 2, type: "view" },
  { _id: 3, type: "click" },
  { _id: 4, type: "view" },
  { _id: 5, type: "purchase" }
]);
```

**查询示例 **

```
db.events.aggregate([
  { $match: { $sampleRate: 0.3 } }
]);
```

**输出**

该操作返回文档的随机子集。因为`$sampleRate`是概率性的，所以每次运行查询时，返回的特定文档及其数量都会有所不同。

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

要查看使用该`$sampleRate`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const db = client.db('test');
    const collection = db.collection('events');

    // Return approximately 30% of the documents
    const result = await collection.aggregate([
      { $match: { $sampleRate: 0.3 } }
    ]).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['events']

        # Return approximately 30% of the documents
        result = list(collection.aggregate([
            { '$match': { '$sampleRate': 0.3 } }
        ]))

        print(result)
    finally:
        client.close()

example()
```

------