

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

8.0.1 版的新功能。

Elastic 叢集不支援。

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()
```

------