$sample - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$sample

Amazon DocumentDB의 $sample 집계 단계는 컬렉션에서 지정된 수의 문서를 무작위로 선택하는 데 사용됩니다. 이는 데이터 분석, 테스트 및 추가 처리를 위한 샘플 생성과 같은 작업에 유용합니다.

파라미터

  • size: 임의로 선택할 문서 수입니다.

예제(MongoDB 쉘)

다음 예제에서는 $sample 스테이지를 사용하여 temp 컬렉션에서 두 문서를 무작위로 선택하는 방법을 보여줍니다.

샘플 문서 생성

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