$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
Choose a size, optionally filter first, then sample.
Decide how many documents you need (size: N, integer ≥ 1).
For a whole-collection sample, put $samplefirst when you can (faster path).
To sample inside a filter, run $match first, then $sample.
Shape fields afterward with $project if you only need a few fields.
Piece
Required?
Role
size
Yes
How many random docs to return
Prior $match
No
Narrow the pool before sampling
First-stage placement
No*
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
Reference
Cheat Sheet
Keep these facts handy while sampling documents.
Topic
Detail
Type
Aggregation stage
Syntax
{ $sample: { size: N } }
size
Integer ≥ 1
vs $limit
Random vs first-N
Fast path
First stage + N < 5% + >100 docs
Oversize N
Returns all available docs
Repeatability
Not guaranteed across runs
Try it
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.
Trace
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)
Code
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.
Keyboard Input inStock
Mouse Input inStock
Monitor Display inStock
Webcam Video out
Headset Audio inStock
Hub Accessories inStock
Pad Accessories inStock
Stand Accessories out
Read the important fields like this:
Field
Example
Plain English
name
"Monitor"
What we show in results
inStock
true
Filter before sampling
category
"Display"
Optional grouping / filter
How It Works
Reset once.drop() keeps demos repeatable.
Mixed stock. Two out-of-stock items are excluded in example 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.
$match first. Drops Webcam and Stand (out of stock). Pool = 6.
$sample next. Picks 2 from that filtered pool only.
Trade-off. Sampling after $match skips the fastest whole-collection cursor path—fine for small sets.
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.
Analysis
Performance Notes
Approach
Cost
Best for
First-stage small N
Pseudo-random cursor
Quick whole-collection previews
$match then sample
Scan / sort filtered set
Random among a subset
Large N (≥ ~5%)
Full read + random sort
When 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.
Remember
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.