0
0
MongodbHow-ToBeginner · 3 min read

How to Use $sample in Aggregation in MongoDB

Use the $sample stage in a MongoDB aggregation pipeline to randomly select a specified number of documents. It takes an object with a size field indicating how many random documents to return.
📐

Syntax

The $sample stage is used inside an aggregation pipeline and requires a size parameter that specifies the number of random documents to return.

  • { $sample: { size: } }: Selects size random documents from the input.
json
[
  { $sample: { size: 5 } }
]
💻

Example

This example shows how to randomly select 3 documents from a collection named products using the aggregation pipeline with $sample.

mongodb
db.products.aggregate([
  { $sample: { size: 3 } }
])
Output
[ { "_id": ObjectId("..."), "name": "Product A", "price": 10 }, { "_id": ObjectId("..."), "name": "Product C", "price": 15 }, { "_id": ObjectId("..."), "name": "Product B", "price": 20 } ]
⚠️

Common Pitfalls

  • Using $sample without specifying size will cause an error because size is required.
  • Requesting a size larger than the collection returns all documents in random order, not an error.
  • $sample can be inefficient on very large collections without indexes; consider performance impact.
mongodb
/* Wrong: Missing size */
db.collection.aggregate([
  { $sample: { size: 0 } }
])

/* Right: Specify size */
db.collection.aggregate([
  { $sample: { size: 5 } }
])
📊

Quick Reference

ParameterDescription
sizeNumber of random documents to return (required)
UsageUsed as a stage in aggregation pipeline
ReturnsRandom documents from input collection
ErrorMissing size causes error
PerformanceMay be slow on large collections without indexes

Key Takeaways

Use $sample with a size parameter inside an aggregation pipeline to get random documents.
Always specify the size; omitting it causes an error.
If size is larger than collection, all documents are returned in random order.
$sample can impact performance on large collections.
Use $sample as a single stage or combined with other aggregation stages.