MongoDB $sampleRate Operator

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

What You’ll Learn

The $sampleRate operator randomly returns true or false for each document at a given probability. Use it in $match with $expr to keep a random percentage of records — ideal for testing, spot checks, and large-scale analytics on a subset.

01

Random Filter

true / false per doc.

02

Rate 0–1

0.1 = ~10% kept.

03

$match + $expr

Primary usage pattern.

04

Probabilistic

Approximate count.

05

Use Cases

QA, A/B, profiling.

06

vs $sample

Rate vs exact n.

Definition and Usage

In MongoDB’s aggregation framework, the $sampleRate operator evaluates to true with a probability equal to the given rate, and false otherwise. For example, { $sampleRate: 0.25 } includes each document roughly 25% of the time.

Unlike the $sample pipeline stage (which picks an exact number of documents), $sampleRate gives you percentage-based sampling. The final count varies slightly run to run, but the average matches your rate over large collections.

💡
Beginner Tip

Always wrap $sampleRate in $match with $expr. A rate of 0.1 means about 10% of documents pass the filter — not exactly 10%, but close on large datasets.

📝 Syntax

The $sampleRate operator takes a single numeric rate between 0 and 1:

mongosh
{ $sampleRate: <rate> }

Typical Usage in $match

mongosh
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $sampleRate: 0.1
      }
    }
  }
])

Syntax Rules

  • rate — a number from 0.0 to 1.0 (inclusive).
  • 0.0 — no documents return true.
  • 1.0 — every document returns true.
  • Returns a boolean per document — use inside $expr in $match.
  • Also usable in $project or $addFields to add a random inclusion flag.
  • Available in MongoDB 4.4+ aggregation expressions.

💡 $sampleRate vs $sample vs $rand

$sampleRate — expression; ~10% with rate 0.1 (approximate count)
$sample — pipeline stage; exact n random documents
$rand — expression; random [0, 1) per doc; combine with $lt for custom rates
Need exact count? → use { $sample: { size: 100 } }

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (sampling)
Syntax{ $sampleRate: <rate> }
Rate range0.0 to 1.0
Outputtrue or false per document
Common usage$match + $expr
10% sample
{
  $expr: {
    $sampleRate: 0.1
  }
}

~1 in 10 docs

50% sample
{
  $sampleRate: 0.5
}

Roughly half

All docs
{
  $sampleRate: 1.0
}

Always true

None
{
  $sampleRate: 0.0
}

Always false

Examples Gallery

Sample event logs, combine sampling with filters, add inclusion flags, and compare rates with $sampleRate.

📚 Basic Random Sampling

Keep roughly 10% of documents from an events collection.

Sample Input Documents

Suppose you have a large events collection:

mongosh
[
  { "_id": 1, "userId": "u1", "action": "click", "status": "ok" },
  { "_id": 2, "userId": "u2", "action": "view", "status": "ok" },
  { "_id": 3, "userId": "u3", "action": "click", "status": "error" },
  { "_id": 4, "userId": "u4", "action": "purchase", "status": "ok" },
  { "_id": 5, "userId": "u5", "action": "click", "status": "ok" }
  // ... thousands more documents
]

Example 1 — Sample 10% of All Events

Randomly include about one in ten documents:

mongosh
db.events.aggregate([
  {
    $match: {
      $expr: {
        $sampleRate: 0.1
      }
    }
  },
  {
    $project: {
      userId: 1,
      action: 1,
      status: 1
    }
  }
])

How It Works

Each document is evaluated independently. $sampleRate: 0.1 gives a 10% chance of returning true. Wrap it in $expr so $match treats it as an aggregation expression.

📈 Combined Filters and Flags

Sample within a subset, or add a boolean field for downstream stages.

Example 2 — Sample 20% of Error Events Only

Apply a regular filter first, then sample within the result:

mongosh
db.events.aggregate([
  {
    $match: {
      status: "error",
      $expr: {
        $sampleRate: 0.2
      }
    }
  }
])

// Only "error" documents are considered;
// ~20% of those pass the random filter.

How It Works

Standard query fields (status: "error") and $expr work together in the same $match. MongoDB applies both conditions.

Example 3 — Add a Random Inclusion Flag

Mark documents for A/B analysis without filtering them out:

mongosh
db.events.aggregate([
  {
    $addFields: {
      inExperiment: {
        $sampleRate: 0.5
      }
    }
  },
  {
    $match: {
      inExperiment: true
    }
  }
])

// ~50% of documents get inExperiment: true

How It Works

$sampleRate can appear in $addFields to store the boolean result. A later $match keeps only the true rows.

Example 4 — Quick QA on Production Data

Inspect a tiny slice of live data without scanning everything downstream:

mongosh
db.orders.aggregate([
  {
    $match: {
      $expr: {
        $sampleRate: 0.01
      }
    }
  },
  {
    $limit: 50
  },
  {
    $project: {
      orderId: 1,
      total: 1,
      createdAt: 1
    }
  }
])

// ~1% sample, capped at 50 docs for review

How It Works

Combine a low rate with $limit for safe manual inspection. The sample reduces load; the limit bounds output size.

Bonus — $sampleRate vs Manual $rand Threshold

These approaches are equivalent in spirit:

mongosh
// Using $sampleRate (simpler)
{ $match: { $expr: { $sampleRate: 0.25 } } }

// Using $rand (more flexible)
{
  $match: {
    $expr: {
      $lt: [ { $rand: {} }, 0.25 ]
    }
  }
}

// Both keep roughly 25% of documents

How It Works

Prefer $sampleRate when a fixed probability is enough. Use $rand when you need the random number for sorting, weighting, or custom logic.

🚀 Use Cases

  • Development and QA — inspect a random slice of production-like data without full exports.
  • Performance testing — run expensive pipelines on a fraction of documents.
  • A/B experiments — randomly assign documents to treatment groups at a set rate.
  • Approximate analytics — estimate metrics on large collections when exact counts are unnecessary.

🧠 How $sampleRate Works

1

MongoDB reads the rate argument

The rate must be a number between 0.0 and 1.0.

Rate
2

Each document gets a random boolean

MongoDB returns true with probability equal to the rate, independently per document.

Random
3

$match keeps true results

When used in $expr, only documents where $sampleRate is true continue in the pipeline.

Filter
=

Random subset (~rate × total)

Output size varies per run but averages to your chosen percentage on large sets.

Conclusion

The $sampleRate operator provides simple probabilistic sampling in MongoDB aggregation pipelines. Pass a rate from 0 to 1, use it inside $match with $expr, and keep approximately that fraction of documents.

For an exact document count, use the $sample stage instead. For custom random logic, consider $rand. Next in the series: $second.

💡 Best Practices

✅ Do

  • Use $expr when placing $sampleRate inside $match
  • Pick low rates (0.01–0.1) for QA on large collections
  • Combine with $limit to cap review output
  • Use $sample when you need an exact document count
  • Document that results are approximate and vary per run

❌ Don’t

  • Expect the exact percentage on tiny collections (variance is high)
  • Use rates outside 0.0–1.0 (invalid or unexpected behavior)
  • Assume the same documents are sampled on every run
  • Use $sampleRate as a standalone pipeline stage
  • Rely on sampling alone for statistically rigorous experiments without further design

Key Takeaways

Knowledge Unlocked

Five things to remember about $sampleRate

Use these points when sampling documents in pipelines.

5
Core concepts
📝 02

Rate 0–1

Probability.

Syntax
🛠 03

$match + $expr

Filter pattern.

Usage
🗃 04

Approximate

Not exact count.

Behavior
05

vs $sample

Rate vs size n.

Compare

❓ Frequently Asked Questions

$sampleRate randomly returns true or false for each document. The argument is a rate between 0 and 1 — for example, 0.25 means each document has roughly a 25% chance of returning true. Use it inside $match with $expr to keep a random subset of documents.
The syntax is { $sampleRate: <rate> }. The rate must be a number from 0.0 to 1.0 inclusive. Common usage: { $match: { $expr: { $sampleRate: 0.1 } } } to sample about 10% of documents.
The rate must be between 0.0 and 1.0. A rate of 0.0 excludes all documents; 1.0 includes all documents; 0.1 includes roughly 10%; 0.5 includes roughly half.
$sampleRate is an expression that probabilistically filters each document by percentage. The $sample pipeline stage selects an exact count (n) of random documents. Use $sampleRate for approximate percentage sampling; use $sample when you need a fixed number.
$sampleRate directly returns true/false at a given rate. $rand returns a random number in [0, 1) per document, which you can compare with $lt for custom thresholds. $sampleRate is simpler when you only need percentage-based inclusion.

Continue the Operator Series

Move on to $second for date extraction, or review $rand for flexible random numbers.

Next: $second →

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