$sample (Random Sample)
Last updated: 2026-10-09
$sample (Random Sample)
$sample randomly selects a specified number of documents — handy for sampling analysis, test data, or random picks. It may not scan the whole collection and randomness is not perfectly uniform, so treat it as an approximate random sample. Output order is random.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $sample: { size: <positive integer> } }
⚙️ Parameters
| size | Number of documents to sample; must be a positive integer. |
|---|
Returns:Randomly sampled document stream
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $sample: pick 5 random users
db.users.aggregate([
{ $sample: { size: 5 } }
])
Output:
// Result may differ on every run
📌 Notes
- Sampling is not strictly uniform; repeated runs differ
- size must be a positive integer
- Unlike $limit, selection is random with unpredictable order
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs $sample uniformly random?
ANot strictly uniform; it uses a pseudo-random mechanism suited to approximate sampling and testing.
QWhat is the difference between $sample and $limit?
A$limit takes the first N in pipeline order; $sample picks N at random with no guaranteed order.
QCan $sample follow $match?
AYes. $sample is a regular stage and can sample filtered results.