$rand

Returns a random floating-point number between 0 and 1, useful for random sampling and generating random values in aggregation pipelines.

Syntax

{ $rand: {} }

Examples

Generate random values

Add random numbers to documents for sampling or testing

Query:

db.products.aggregate([{ $project: { name: 1, randomValue: { $rand: {} } } }])

Output:

Products with added randomValue field containing random float between 0 and 1

Random sampling

Use random values for probabilistic document selection

Query:

db.users.aggregate([{ $project: { userId: 1, randomSample: { $rand: {} } } }, { $match: { randomSample: { $lt: 0.1 } } }])

Output:

Returns approximately 10% of users selected randomly using random sampling

Related