本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$sampleRate
8.0.1 版中的新增内容。
弹性集群不支持。
Amazon DocumentDB 中的$sampleRate运算符根据指定速率对输入文档的随机样本进行匹配。您可以在find()查询筛选器或聚合$match阶段使用它。由于选择是概率性的,因此返回的文档数量是近似值,并且可能因运行而异。
参数
示例(MongoDB Shell)
以下示例使用$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是概率性的,所以每次运行查询时,返回的特定文档及其数量都会有所不同。
代码示例
要查看使用该$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()