MongoDB $sample Stage

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

What Is $sample?

$sample is a MongoDB aggregation stage that picks N documents at random from its input—handy for demos, spot checks, and quick analytics previews.

Remember
$sample = "pick N random documents"

{ $sample: { size: 3 } }

size ≥ 1 (positive integer)
fewer docs than size → return all of them
results change each run (not deterministic)

$limit → first N in order
$sample → random N
UsePrefer
Random subset / preview$sample
Top-N or paginated lists$limit (+ $sort)
Random among a filter$match then $sample

How to Use $sample in MongoDB

Choose a size, optionally filter first, then sample.

  1. Decide how many documents you need (size: N, integer ≥ 1).
  2. For a whole-collection sample, put $sample first when you can (faster path).
  3. To sample inside a filter, run $match first, then $sample.
  4. Shape fields afterward with $project if you only need a few fields.
PieceRequired?Role
sizeYesHow many random docs to return
Prior $matchNoNarrow the pool before sampling
First-stage placementNo*Enables the faster cursor path

*Also needs N < ~5% of the collection and more than 100 documents.

Pseudocode

Pseudocode
input = documents from collection (or prior stage)
N = size

if N >= count(input):
  emit all of input
else:
  pick N distinct docs at random from input
  emit those N docs

// Order of emitted docs is not a sorted ranking
// Next run may pick a different set

Cheat Sheet

Keep these facts handy while sampling documents.

TopicDetail
TypeAggregation stage
Syntax{ $sample: { size: N } }
sizeInteger ≥ 1
vs $limitRandom vs first-N
Fast pathFirst stage + N < 5% + >100 docs
Oversize NReturns all available docs
RepeatabilityNot guaranteed across runs

Live Preview

Pick a random subset from eight products (teaching model of { $sample: { size: N } }). Click again to reshuffle.

Each click picks a new random set (like re-running the pipeline).

Result
Click “Run $sample” to pick random products.

Worked Walkthrough — Three Random Products

Eight products in a collection. Goal: return any three at random.

Calculation
Collection (8 docs):
  Keyboard, Mouse, Monitor, Webcam,
  Headset, Hub, Pad, Stand

{ $sample: { size: 3 } }

One possible run → Monitor, Pad, Keyboard
Next run         → Webcam, Mouse, Hub
                  (different set — that is expected)

If size were 20 → all 8 docs (cannot invent more)

MongoDB Examples

We use a small products collection. First sample the whole set, then sample only in-stock items. Run these in mongosh after inserting the sample data once. Random output varies by run; View Output shows one possible result.

Example 1 — Sample Data

Eight products with a category and stock flag—enough to demo whole-collection and filtered sampling.

mongosh
db.products.drop();
db.products.insertMany([
  { name: "Keyboard", category: "Input",  inStock: true,  price: 49 },
  { name: "Mouse",    category: "Input",  inStock: true,  price: 29 },
  { name: "Monitor",  category: "Display", inStock: true,  price: 199 },
  { name: "Webcam",   category: "Video",  inStock: false, price: 79 },
  { name: "Headset",  category: "Audio",  inStock: true,  price: 89 },
  { name: "Hub",      category: "Accessories", inStock: true,  price: 39 },
  { name: "Pad",      category: "Accessories", inStock: true,  price: 15 },
  { name: "Stand",    category: "Accessories", inStock: false, price: 35 }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.products.find({}, { name: 1, category: 1, inStock: 1, _id: 0 })

Read the important fields like this:

FieldExamplePlain English
name"Monitor"What we show in results
inStocktrueFilter before sampling
category"Display"Optional grouping / filter

How It Works

  1. Reset once. drop() keeps demos repeatable.
  2. Mixed stock. Two out-of-stock items are excluded in example 3.
  3. Small set on purpose. Easy to see that $sample picks a subset.

Example 2 — Random N

Goal: return three random products from the whole collection. Re-run the pipeline to see different names.

mongosh
db.products.aggregate([
  { $sample: { size: 3 } },
  { $project: { name: 1, category: 1, _id: 0 } }
]);

How It Works

  1. $sample first. Picks 3 docs from all 8 products.
  2. $project trims fields. Only name and category in the response.
  3. Not sorted by price. Order/set is random, not a ranking.
  4. Run again. You will often get a different trio.

Example 3 — Filter Then Sample

Goal: randomly pick two products that are in stock only.

mongosh
db.products.aggregate([
  { $match: { inStock: true } },
  { $sample: { size: 2 } },
  { $project: { name: 1, price: 1, _id: 0 } }
]);

How It Works

  1. $match first. Drops Webcam and Stand (out of stock). Pool = 6.
  2. $sample next. Picks 2 from that filtered pool only.
  3. Trade-off. Sampling after $match skips the fastest whole-collection cursor path—fine for small sets.
  4. Use this pattern whenever randomness must respect a filter.

Edge Cases & Pitfalls

Check these before relying on $sample in production pipelines.

random

Results are not stable

Do not use $sample for paginated APIs or ranked lists. Persist a sample with $out / $merge if you need a fixed set.

size

size must be ≥ 1

Pass a positive integer. Unlike $limit, a zero or negative size is invalid for $sample.

perf

Large samples scan more

If N is ≥ ~5% of the collection (or $sample is not first), MongoDB reads all input and random-sorts—watch memory limits.

views

Views never get the fast path

On a view, $sample is appended after the view pipeline, so it is never the first stage.

Performance Notes

ApproachCostBest for
First-stage small NPseudo-random cursorQuick whole-collection previews
$match then sampleScan / sort filtered setRandom among a subset
Large N (≥ ~5%)Full read + random sortWhen you truly need a big sample

Keep size small for interactive tools. Prefer first-stage $sample for collection-wide peeks. Filter first only when the random pool must match a condition.

Key Takeaways

  • Role: return up to N random documents.
  • Syntax: { $sample: { size: N } }.
  • vs $limit: random, not first-N.
  • Perf: first stage + small N is fastest.

One line: $sample answers “give me N random documents from here.”

Frequently Asked Questions

$sample randomly selects up to N documents from the documents entering the stage. Syntax: { $sample: { size: N } }. Use it for spot checks, demos, analytics previews, or random subsets inside aggregation.
{ $sample: { size: <positive integer> } }. Example: { $sample: { size: 3 } } returns up to three random documents. size must be an integer greater than or equal to 1.
$limit keeps the first N documents in the current pipeline order (deterministic). $sample picks N documents at random (non-deterministic). Use $limit after $sort for top-N; use $sample when you need randomness.
As the first stage, when N is under about 5% of the collection and the collection has more than 100 documents, MongoDB can use a fast pseudo-random cursor. Otherwise it reads all input and does a random sort.
$sample returns all available documents—never more than exist. If the input has 7 docs and size is 10, you get 7.
No. Each pipeline run can return a different set. To keep a fixed sample, run $sample once and write results with $out or $merge.

Next: $search

Full-text and fuzzy search with Atlas Search in the pipeline.

$search tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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