$rand - Amazon DocumentDB

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

$rand

버전 8.0의 새로운 기능

Amazon DocumentDB의 $rand 연산자는 0에서 1 사이의 난수를 생성하는 데 사용됩니다.

파라미터

없음

예제(MongoDB 쉘)

다음 예제에서는 $rand 연산자를 사용하여 temp 컬렉션에서 두 문서를 무작위로 선택하는 방법을 보여줍니다.

샘플 문서 생성

db.items.insertMany([ { "name": "pencil", "quantity": 110 }, { "name": "pen", "quantity": 159 } ])

쿼리 예제

db.items.aggregate([ { $project: { randomValue: { $rand: {} } } } ])

출력

[ { _id: ObjectId('6924a5edd66dcae121d29517'), randomValue: 0.8615243955294392 }, { _id: ObjectId('6924a5edd66dcae121d29518'), randomValue: 0.22815483022099903 } ]

코드 예제

$rand 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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('items'); const result = await collection.aggregate([ { $project: { randomValue: { $rand: {} } } } ]).toArray(); console.log(result); 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') db = client['test'] collection = db['items'] result = list(collection.aggregate([ { "$project": { "randomValue": { "$rand": {} } } } ])) print(result) client.close() example()