MongoDB $rand Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $rand?

$rand is a MongoDB aggregation expression that returns a random floating-point number in the half-open range [0, 1)—at least 0, and always less than 1. Each document gets its own value.

Remember
$rand = random float in [0, 1)

{ $rand: {} }

no arguments — always empty {}
per document → independent value
not stable across runs

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

exact count → use $sample stage instead
UsePrefer
Random number / % sample$rand
Exact N random docs$sample
Integer sequence$range

How to Use $rand in MongoDB

Call { $rand: {} }, then store it, scale it, or filter with it.

  1. Choose an expression stage ($addFields or $project).
  2. Write { $rand: {} } (empty object only).
  3. Optionally scale with $multiply / $floor for ranges.
  4. For percentage sampling, compare with $lt inside $match + $expr.
PieceRequired?Role
{}YesEmpty object — no options
Output—Float in [0, 1)
$lt + rateNoKeep ~N% of documents

Pseudocode

Pseudocode
for each document:
    r = random_float()   // 0 ≤ r < 1

    // store
    emit { ..., score: r }

    // or keep ~20%
    if r < 0.2:
        keep document
    else:
        skip

Cheat Sheet

Keep these facts handy while adding randomness to pipelines.

TopicDetail
TypeAggregation expression (not a find filter alone)
Syntax{ $rand: {} }
Range[0, 1)
ArgsNone — object must be empty
StabilityDifferent every run
~20% sample$lt: [ { $rand: {} }, 0.2 ]
vs $sampleRate vs exact count

Live Preview

Generate a fresh [0, 1) value (like $rand), and optionally scale it to a dice roll 1–6.

Simulates { $rand: {} }. Each click draws a new number.

Result
$rand → (click Run for a new value)

range: 0 ≤ r < 1

Worked Walkthrough — Random Ticket Score

Three support tickets sit in a queue. We give each a random score in [0, 1), then keep only tickets with score < 0.2 (about 20%).

Calculation
Documents:
  A, B, C

Each gets:
  score = $rand → e.g. 0.41, 0.07, 0.88
                 (your numbers will differ)

Keep if score < 0.2:
  A 0.41 → skip
  B 0.07 → keep
  C 0.88 → skip

About 1 in 5 docs kept on average.

MongoDB Examples

We use three tickets. First insert them, then attach a random score, then keep roughly 20% with $match. Run these in mongosh. Your random numbers will differ each run.

Example 1 — Sample Data

Imagine three support tickets: Login, Billing, and Shipping. We save them in a collection named tickets.

mongosh
db.tickets.insertMany([
  { _id: 1, topic: "Login" },
  { _id: 2, topic: "Billing" },
  { _id: 3, topic: "Shipping" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in tickets. Run find() to see them:

mongosh
db.tickets.find()

Read those documents like this:

Field in MongoDBValuesPlain English
_id1, 2, 3Document ids
topicLogin / Billing / ShippingWhat the ticket is about
Picture
Login     →  $rand → 0.??
Billing   →  $rand → 0.??
Shipping  →  $rand → 0.??

each draw independent, in [0, 1)

How It Works

  1. Insert once. insertMany adds three ticket documents.
  2. No random field yet. We will attach $rand in Example 2.
  3. find() shows the same shape. Ready for the next step.

Example 2 — Add $rand Score

Goal: give every ticket a random score in [0, 1).

mongosh
db.tickets.aggregate([
  {
    $addFields: {
      score: { $rand: {} }
    }
  }
]);

How It Works

  1. Same three tickets. Still using the documents from Example 1.
  2. Draw per document. { $rand: {} } returns a float in [0, 1) for each row.
  3. Store as score. $addFields writes the new score field.

Example 3 — Keep ~20%

Same tickets, but keep only those whose fresh random draw is less than 0.2 (about one in five on average).

mongosh
db.tickets.aggregate([
  {
    $match: {
      $expr: {
        $lt: [ { $rand: {} }, 0.2 ]
      }
    }
  }
]);

How It Works

  1. Draw again. $match evaluates a new $rand per document.
  2. Compare to 0.2. $lt keeps the doc only when the draw is below the rate.
  3. Expect variation. With only three docs, a single run may keep 0–3 tickets.

Edge Cases & Pitfalls

Check these before relying on $rand in production pipelines.

args

Empty object only

Write { $rand: {} }. There is no seed argument and no min/max options on the operator itself.

stable

Not reproducible

Each run can differ. Do not use $rand for stable ids, caching keys, or audits that must match yesterday’s output.

count

Need exact N?

Percentage filters with $rand are approximate. Use the $sample stage for a fixed document count.

scale

Integers need math

For 1–6 style rolls, combine $multiply, $floor, and $add. $rand alone is always a float in [0, 1).

Performance Notes

ApproachCostBest for
$rand + $addFieldsCheap per docScores / shuffle keys
$match + rateScan + filter~percentage samples
$sample stageOptimized pickExact N documents

Drawing a float is cheap, but filtering a huge collection still reads many docs. Prefer $sample when you only need a fixed-size random subset.

Key Takeaways

  • Role: random float in [0, 1) per document.
  • Syntax: always { $rand: {} }.
  • Sampling: $lt vs a rate for ~percent; $sample for exact N.
  • Caution: results change every run.

One line: $rand answers “give this document a fresh number in [0, 1).”

Frequently Asked Questions

$rand returns a random floating-point number greater than or equal to 0 and less than 1 for each document. Use it in aggregation for sampling, shuffling, test fields, and probabilistic filters.
Use { $rand: {} }. It takes an empty object and accepts no arguments. Place it inside stages such as $addFields, $project, or $match with $expr.
The range is [0, 1)—inclusive of 0, exclusive of 1. Each document gets its own independent random value.
Use $match with $expr: { $match: { $expr: { $lt: [ { $rand: {} }, 0.2 ] } } }. Change 0.2 to any rate between 0 and 1.
$rand gives a random number per document for custom logic. The $sample stage picks a fixed count of documents. Prefer $sample for an exact size; prefer $rand for percentage-based or custom random rules.
No. Each pipeline run (and each evaluation) can produce different numbers. Do not rely on $rand for stable ids or reproducible reports.

Next: $range

Generate arrays of integers for loops and indexes.

$range tutorial →

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.

9 people found this page helpful