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

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $sample: { size: <positive integer> } }

⚙️ Parameters

sizeNumber 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏