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.
Fundamentals
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.
Foundation
📝 Syntax
The $sampleRate operator takes a single numeric rate between 0 and 1:
// On 5 docs, you might get 0–2 results (random each run).
// On 10,000 docs, expect roughly ~1,000 documents.
// Exact count varies; average ≈ rate × total.
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:
Prefer $sampleRate when a fixed probability is enough. Use $rand when you need the random number for sorting, weighting, or custom logic.
Applications
🚀 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $sampleRate
Use these points when sampling documents in pipelines.
5
Core concepts
🎲01
Random Boolean
true / false.
Purpose
📝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.