MongoDB $sampleRate Operator

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

What Is $sampleRate?

$sampleRate is a MongoDB aggregation expression that randomly keeps documents at a given probability. Pass a rate from 0 to 1 (for example 0.33 ≈ one in three). Use it inside $match.

Remember
$sampleRate = keep ~rate × 100% of docs

{ $match: { $sampleRate: 0.33 } }

rate  → 0 … 1 (inclusive)
0     → keep none
1     → keep all
0.1   → keep ~10%

same idea as:
  $lt: [ { $rand: {} }, 0.33 ]

exact count → use $sample stage
UsePrefer
~percentage sample$sampleRate
Exact N random docs$sample
Custom random float / rules$rand

How to Use $sampleRate in MongoDB

Pick a rate, put it in $match, then continue the pipeline on the kept docs.

  1. Choose a rate between 0 and 1 (for example 0.2 for ~20%).
  2. Add { $match: { $sampleRate: <rate> } } early in the pipeline.
  3. Optionally $count or project the kept documents.
  4. If you need an exact size instead, switch to the $sample stage.
PieceRequired?Role
$matchYesStage that applies the filter
$sampleRateYesProbability each document is kept
RateYesNumber in [0, 1]

Pseudocode

Pseudocode
rate = 0.33   // keep about 1 in 3

for each document:
    // same idea as: random() < rate
    if coin_flip(probability = rate):
        keep document
    else:
        skip

// next run can keep a different set

Cheat Sheet

Keep these facts handy while sampling documents.

TopicDetail
TypeAggregation expression (used in $match)
Syntax{ $match: { $sampleRate: <rate> } }
Rate0 … 1 inclusive
DistributionUniform — each doc independent
StabilityDifferent every run
≈ $rand$lt: [ { $rand: {} }, rate ]
vs $sampleRate (%) vs exact count

Live Preview

Simulate $sampleRate over a small set of documents. Click again — the kept count will change.

Simulates { $match: { $sampleRate: rate } } on 6 sample events.

Result
rate = 0.33 on 6 docs
expected ≈ 2 kept

(click Run for a new draw)

Worked Walkthrough — Keep ~33% of Events

Six event logs enter the pipeline. With rate 0.33, each event has about a one-in-three chance of surviving $match.

Calculation
Documents: E1 … E6  (6 total)
rate = 0.33

For each event:
  keep with probability 0.33

Example run (yours will differ):
  E1 keep · E2 skip · E3 keep · E4 skip · E5 skip · E6 skip
  → 2 kept  (expected ≈ 6 × 0.33 ≈ 2)

Small sets vary a lot; large sets stay closer to the rate.

MongoDB Examples

We use six events. First insert them, then keep about one third with $sampleRate, then count how many survived. Run these in mongosh. Kept sets differ each run.

Example 1 — Sample Data

Imagine six app events: login, click, purchase, and a few more. We save them in a collection named events.

mongosh
db.events.insertMany([
  { _id: 1, type: "login" },
  { _id: 2, type: "click" },
  { _id: 3, type: "purchase" },
  { _id: 4, type: "click" },
  { _id: 5, type: "logout" },
  { _id: 6, type: "click" }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.events.find()

Read those documents like this:

Field in MongoDBValuesPlain English
_id1 … 6Document ids
typelogin / click / …What kind of event it is
Picture
6 events enter the pipeline

  login · click · purchase · click · logout · click

$sampleRate: 0.33  →  keep ~2 of them
(exact ids change every run)

How It Works

  1. Insert once. insertMany adds six event documents.
  2. No sampling yet. All six rows are stored as written.
  3. find() shows the same shape. Ready for $sampleRate next.

Example 2 — Keep ~33%

Goal: randomly keep about one third of the events using $sampleRate inside $match.

mongosh
db.events.aggregate([
  {
    $match: {
      $sampleRate: 0.33
    }
  }
]);

How It Works

  1. Read all six events. Each document reaches $match.
  2. Flip a coin per doc. $sampleRate: 0.33 keeps it with probability 0.33.
  3. Pass survivors forward. Dropped docs never reach later stages.
  4. Same as $rand. This is equivalent to $lt: [ { $rand: {} }, 0.33 ] inside $expr.

Example 3 — Count Kept Docs

Same rate, but end with $count so you only see how many documents survived (handy for checking the rate).

mongosh
db.events.aggregate([
  { $match: { $sampleRate: 0.33 } },
  { $count: "numMatches" }
]);

How It Works

  1. Sample first. $match + $sampleRate keeps a random subset.
  2. Count survivors. $count returns one document with numMatches.
  3. Expect variation. With only six rows, one run can be far from two kept docs.

Edge Cases & Pitfalls

Check these before using $sampleRate in production pipelines.

count

Approximate, not exact

Rate 0.1 does not guarantee exactly 10%. Use $sample when you need a fixed document count.

stable

Results change every run

Selection is non-deterministic. Do not rely on the same ids being kept tomorrow.

size

Small sets swing more

With few documents, kept counts jump around. Larger collections land closer to rate × N.

range

Rate must be 0–1

Pass a float from 0 to 1. Values outside that range are invalid for normal percentage sampling.

Performance Notes

ApproachCostBest for
$sampleRate in $matchScan + coin flip~percentage of a stream
$rand + $ltSimilarCustom thresholds / logic
$sample stageOptimized pickExact N documents

A coin flip is cheap, but the stage still sees every input document. Prefer $sample when you only need a small fixed-size random subset from a huge collection.

Key Takeaways

  • Role: keep ~rate × 100% of documents at random.
  • Syntax: { $match: { $sampleRate: <0…1> } }.
  • Twin: same idea as $rand + $lt.
  • Exact N: use the $sample stage instead.

One line: $sampleRate answers “keep about this percent of documents at random.”

Frequently Asked Questions

$sampleRate randomly keeps documents as they pass through the pipeline. The rate is a number from 0 to 1 — for example, 0.33 means each document has about a 33% chance of being selected.
Use { $match: { $sampleRate: <rate> } }. The rate must be between 0 and 1 inclusive. Example: { $match: { $sampleRate: 0.1 } } keeps about 10% of documents.
No. $sampleRate is a percentage-style filter (approximate count). The $sample stage picks an exact number of random documents. Use $sample when you need a fixed size.
{ $match: { $sampleRate: 0.33 } } is equivalent to { $match: { $expr: { $lt: [ { $rand: {} }, 0.33 ] } } }. $sampleRate is the shorter form for percentage sampling.
Selection is non-deterministic. Small collections vary more; larger ones tend to land closer to rate × total documents.
The usual, documented pattern is inside $match. For custom random logic or storing a random float, use $rand instead.

Next: $second

Pull the seconds component from a date in aggregation.

$second 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