Introduction to MongoDB $rand Operator

The $rand operator is a built-in operator in MongoDB used to generate a random number between [0,1). It can be used in aggregation pipelines, such as in the $project or $addFields stages. By using the $rand operator, we can generate random values and store them in documents or perform other operations.

Syntax

The syntax of the $rand operator is as follows:

{ $rand: <seed> }

Where <seed> is an optional parameter and can be any integer value. If <seed> is specified, the same sequence of random numbers will be generated every time the $rand operator is used. If <seed> is not specified, the MongoDB system time is used as the default seed.

Use Cases

The $rand operator is commonly used in the following scenarios:

  • Generate random values and store them in documents for subsequent calculations or queries.
  • Randomly select document samples in the $sample stage.
  • Generate randomly ordered results.

Examples

Example 1: Generate Random Values and Store Them in Documents

Suppose we have a collection containing product prices, and we want to add a field named “discount” to each product with a random value between 10% and 20% of the product price. We can use the following aggregation pipeline to achieve this:

db.products.aggregate([
  { $addFields: { discount: { $multiply: [{ $rand: {} }, 0.1] } } }
])

In the above example, we use the $rand operator to generate a random number, then multiply it by 0.1 to get a random number between 10% and 20%, and store it in the “discount” field.

Example 2: Randomly Order Results

Suppose we have a collection containing student scores, and we want to randomly order the scores. We can use the following aggregation pipeline to achieve this:

db.scores.aggregate([
  { $addFields: { random: { $rand: {} } } },
  { $sort: { random: 1 } },
  { $project: { random: 0 } }
])

In the above example, we use the $rand operator to generate a random number for each document and store it in a field named random. Then we use the $sort stage to sort the documents in ascending order based on the random field, achieving a randomly ordered result. Finally, we use the $project stage to exclude the random field from the result.

Conclusion

The $rand operator is a very useful built-in operator in MongoDB that can be used in many scenarios such as generating random numbers, randomly ordering results, and more. We can use the $rand operator to generate random numbers in aggregation pipelines.