$sample - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$sample

Amazon DocumentDB の$sample集約ステージは、コレクションから指定された数のドキュメントをランダムに選択するために使用されます。これは、データ分析、テスト、さらに処理するためのサンプルの生成などのタスクに役立ちます。

パラメータ

  • size: ランダムに選択するドキュメントの数。

例 (MongoDB シェル)

次の例は、 $sampleステージを使用してtempコレクションから 2 つのドキュメントをランダムに選択する方法を示しています。

サンプルドキュメントを作成する

db.temp.insertMany([ { "_id": 1, "temperature": 97.1, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 2, "temperature": 98.2, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 3, "temperature": 96.8, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 4, "temperature": 97.9, "humidity": 0.61, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 5, "temperature": 97.5, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 6, "temperature": 98.0, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 7, "temperature": 97.2, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 8, "temperature": 98.1, "humidity": 0.59, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 9, "temperature": 96.9, "humidity": 0.62, "timestamp": ISODate("2019-03-21T21:17:22.425Z") }, { "_id": 10, "temperature": 97.7, "humidity": 0.60, "timestamp": ISODate("2019-03-21T21:17:22.425Z") } ]);

クエリの例

db.temp.aggregate([ { $sample: { size: 2 } } ])

出力

{ "_id" : 4, "temperature" : 97.9, "humidity" : 0.61, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") } { "_id" : 9, "temperature" : 96.9, "humidity" : 0.62, "timestamp" : ISODate("2019-03-21T21:17:22.425Z") }

結果が示すように、10 件のドキュメントのうち 2 件がランダムにサンプリングされました。これらのドキュメントを使用して平均を決定したり、最小/最大計算を実行したりできます。

コードの例

$sample コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

Node.js
const { MongoClient } = require('mongodb'); async function sampleDocuments() { 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('temp'); const result = await collection.aggregate([ { $sample: { size: 2 } } ]).toArray(); console.log(result); await client.close(); } sampleDocuments();
Python
from pymongo import MongoClient def sample_documents(): 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['temp'] result = list(collection.aggregate([ { '$sample': { 'size': 2 } } ])) print(result) client.close() sample_documents()