$ rand - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$ rand

Baru dari versi 8.0

$randOperator di Amazon DocumentDB digunakan untuk menghasilkan angka acak antara 0 dan 1.

Parameter

Tidak ada

Contoh (MongoDB Shell)

Contoh berikut menunjukkan bagaimana menggunakan $rand operator untuk secara acak memilih dua dokumen dari koleksi. temp

Buat dokumen sampel

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

Contoh kueri

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

Keluaran

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

Contoh kode

Untuk melihat contoh kode untuk menggunakan $rand perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

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