$percentile (Percentile Accumulator)

Last updated: 2026-10-09

$percentile (Percentile Accumulator)

$percentile is an accumulator returning values at given percentiles (0 to 100) of a field within a group, available since MongoDB 7.0. The p argument accepts a single value or an array. method supports approximate (default, faster) and exact. Common for p95/p99 latency and salary quantiles.

CategoryAccumulators
MongoDB Version7.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $group: { _id: <key>, pct: { $percentile: { input: "$field", p: [ <percentile> ], method: "approximate" } } } }

Returns:Values at the requested percentiles (array in, array out)

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $percentile: p50, p95, p99 latency per service
db.latency.aggregate([
  { $group: { _id: '$service', pct: { $percentile: { input: '$ms', p: [50, 95, 99], method: 'approximate' } } } }
])

Output:

{ "_id": "api", "pct": [12, 45, 80] }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow do I compute p95?
APass p: [95] to get that quantile, commonly used for latency monitoring.
QHow accurate is approximate?
AErrors are small on large datasets and it is fast — fine for monitoring; use exact when precision matters.
QWhat is the difference between $percentile and $median?
A$median is fixed at the 50th percentile; $percentile covers any percentile.
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%

🙏 帮我们做得更好

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

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