MongoDB $rand Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Random

What You’ll Learn

The $rand operator generates a random floating-point number between 0 and 1 for each document in an aggregation pipeline. Use it for sampling, shuffling, A/B testing, and any workflow that needs probabilistic logic.

01

Random [0, 1)

One value per document.

02

Empty Syntax

{ $rand: {} }

03

Sampling

Filter by threshold.

04

Shuffle

Sort on random field.

05

Use Cases

Tests, lotteries, A/B.

06

vs $sample

Flexible vs fixed count.

Definition and Usage

In MongoDB’s aggregation framework, the $rand operator returns a pseudo-random double in the range [0, 1) — that is, greater than or equal to 0 and less than 1. Each document evaluated in the pipeline receives its own independent random value.

Unlike stages that pick a fixed number of documents (such as $sample), $rand gives you a numeric value you can compare, sort, scale, or store. This makes it ideal for percentage-based sampling and custom random logic.

💡
Beginner Tip

$rand takes no arguments — always write { $rand: {} }. Use it inside $project or $addFields to add a random field, or inside $match with $expr to filter probabilistically.

📝 Syntax

The $rand operator takes an empty object (no parameters):

mongosh
{ $rand: {} }

Syntax Rules

  • No arguments — the object must be empty: {}.
  • Output range — [0, 1): includes 0, excludes 1.
  • Per document — each document gets a new random value when evaluated.
  • Use inside $project, $addFields, $set, or $match with $expr.
  • Available in MongoDB 4.4.1 and later.
  • Not a query filter on its own — wrap in an expression stage.

💡 $rand vs $sample vs $sampleRate

$rand — returns [0, 1) per doc; flexible filtering, sorting, scaling
$sample — stage that picks exactly N random documents
$sampleRate — query operator: { $sampleRate: 0.2 } in $match for ~20% pass rate
20% with $rand{ $expr: { $lt: [ { $rand: {} }, 0.2 ] } }

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (random)
Syntax{ $rand: {} }
Output range[0, 1) — 0 inclusive, 1 exclusive
ArgumentsNone (empty object)
Common stages$project, $addFields, $match + $expr
Basic
{
  randomScore: {
    $rand: {}
  }
}

Add random field

20% sample
$expr: {
  $lt: [
    { $rand: {} },
    0.2
  ]
}

~20% of docs

Shuffle
$sort: {
  shuffle: 1
}

After $rand field

0–99 int
{
  $floor: {
    $multiply: [
      { $rand: {} },
      100
    ]
  }
}

Scale to integer

Examples Gallery

Add random scores, sample a percentage of users, shuffle results, and scale random values to integer ranges.

📚 Add a Random Score

Assign each document a random value between 0 and 1 with $project.

Sample Input Documents

Suppose you have a users collection:

mongosh
[
  { "_id": 1, "name": "Alice", "plan": "pro" },
  { "_id": 2, "name": "Bob",   "plan": "free" },
  { "_id": 3, "name": "Carol", "plan": "pro" },
  { "_id": 4, "name": "Dave",  "plan": "free" },
  { "_id": 5, "name": "Eve",   "plan": "pro" }
]

Example 1 — Basic $rand in $project

Add a randomScore field to every document:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      plan: 1,
      randomScore: { $rand: {} }
    }
  }
])

How It Works

Each document gets an independent random double. Values change on every pipeline run, which is expected for pseudo-random generation.

📈 Practical Patterns

Percentage sampling, shuffling, integer ranges, and A/B assignment.

Example 2 — Random 20% Sample with $match

Keep documents where the random value is below 0.2 (roughly 20%):

mongosh
db.users.aggregate([
  {
    $match: {
      $expr: {
        $lt: [ { $rand: {} }, 0.2 ]
      }
    }
  },
  {
    $project: {
      name: 1,
      plan: 1
    }
  }
])

How It Works

Because $rand is uniformly distributed in [0, 1), comparing it to 0.2 gives each document a ~20% chance of passing. The exact count varies per run.

Example 3 — Shuffle Documents with $sort

Add a random field, sort by it, and limit results for a shuffled pick:

mongosh
db.products.aggregate([
  {
    $addFields: {
      shuffle: { $rand: {} }
    }
  },
  { $sort: { shuffle: 1 } },
  { $limit: 5 },
  {
    $project: {
      name: 1,
      price: 1
    }
  }
])

How It Works

Sorting on a random field produces a different document order each run. Use $limit to pick a random subset without the $sample stage.

Example 4 — A/B Test Assignment

Split users into group A or B based on a random threshold:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      testGroup: {
        $cond: {
          if: { $lt: [ { $rand: {} }, 0.5 ] },
          then: "A",
          else: "B"
        }
      }
    }
  }
])

How It Works

Users with $rand < 0.5 go to group A; the rest go to B. Pair $rand with $cond for simple 50/50 splits or adjust the threshold for uneven groups.

Bonus — Scale to Integer Range (0–99)

Multiply by 100 and floor for a random integer:

mongosh
db.lottery.aggregate([
  {
    $project: {
      ticketId: 1,
      luckyNumber: {
        $floor: {
          $multiply: [ { $rand: {} }, 100 ]
        }
      }
    }
  }
])

// luckyNumber: 0 through 99

How It Works

$rand gives [0, 1). Multiplying by 100 gives [0, 100), and $floor truncates to integers 0–99. Change the multiplier for different ranges.

🚀 Use Cases

  • Random sampling — select a percentage of documents for analysis or QA.
  • A/B testing — assign users to experiment groups with $cond and $rand.
  • Shuffling — randomize document order before $limit for fair picks.
  • Test data — generate random scores, weights, or lottery numbers in pipelines.

🧠 How $rand Works

1

Pipeline reaches $rand

When a stage evaluates { $rand: {} }, MongoDB invokes its random number generator for each document.

Input
2

A random double is produced

Each document receives a value in [0, 1) — independent of other documents in the same evaluation.

Generate
3

The value is used or stored

Store it in a field, compare it in $match, sort on it, or scale it with $multiply.

Output
=

Probabilistic pipelines

Sample, shuffle, split, or score documents with built-in randomness.

Conclusion

The $rand operator generates random numbers in [0, 1) inside MongoDB aggregation pipelines. With no arguments and simple syntax, it powers sampling, shuffling, A/B tests, and custom probabilistic filters.

Remember each run produces different values, and percentage sampling is approximate. Next in the series: $range.

💡 Best Practices

✅ Do

  • Use { $rand: {} } with an empty object
  • Compare to a threshold in $expr for percentage sampling
  • Pair with $cond for A/B group assignment
  • Use $sample when you need an exact document count
  • Scale with $multiply and $floor for integer ranges

❌ Don’t

  • Pass arguments to $rand (it accepts none)
  • Expect identical results on every pipeline run
  • Assume percentage samples are exact counts
  • Use $rand as a top-level query filter without $expr
  • Rely on it for cryptographic security (it is pseudo-random)

Key Takeaways

Knowledge Unlocked

Five things to remember about $rand

Use these points when adding randomness to aggregation pipelines.

5
Core concepts
📝 02

Empty Object

{ $rand: {} }

Syntax
🛠 03

% Sampling

$lt threshold.

Pattern
🔀 04

Shuffle

Sort on random field.

Use case
05

Non-deterministic

Changes each run.

Edge case

❓ Frequently Asked Questions

$rand generates a random floating-point number between 0 (inclusive) and 1 (exclusive) for each document in an aggregation pipeline. Use it for sampling, shuffling, test data, and probabilistic logic.
The syntax is { $rand: {} }. It takes an empty object and accepts no arguments. Use it inside stages like $project, $addFields, or $match with $expr.
$rand returns a value in the range [0, 1) — greater than or equal to 0 and less than 1. Each document gets its own independent random value.
Use $match with $expr: { $match: { $expr: { $lt: [ { $rand: {} }, 0.2 ] } } } } to keep roughly 20% of documents. Adjust the threshold (0.2) for your desired sample rate.
$rand adds a random number per document for flexible filtering or sorting. The $sample stage randomly selects a fixed number of documents from the pipeline. Use $sample when you need an exact count; use $rand for percentage-based or custom random logic.

Continue the Operator Series

Move on to $range for generating sequences, or review $cond for conditional logic.

Next: $range →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful