$bucketAuto (Auto Bucket)

Last updated: 2026-10-09

$bucketAuto (Auto Bucket)

$bucketAuto distributes documents into a specified number of buckets with roughly equal counts, computing boundaries from the value distribution — no manual bounds needed. granularity snaps boundaries to canonical number sequences. Each output document's _id is a { min, max } boundary object. Great for auto histograms and distribution overviews.

CategoryGrouping & Window
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $bucketAuto: { groupBy: <expression>, buckets: <positive integer>, output: { <field>: <accumulator> }, granularity: <granularity> } }

⚙️ Parameters

groupByExpression that determines bucket membership.
bucketsDesired number of buckets; must be a positive integer.
outputPer-bucket accumulators, e.g. $avg or $sum.
granularityCanonical number sequence for boundaries, e.g. R5, 1-2-5, E12, POWERSOF2.

Returns:One { _id: { min, max }, count, ... } document per bucket

▶ Example

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

// $bucketAuto: split into 4 buckets, average per bucket
db.scores.aggregate([
  { $bucketAuto: {
    groupBy: '$score',
    buckets: 4,
    output: { avg: { $avg: '$score' } }
  } }
])

Output:

{ "_id": { "min": 0, "max": 45 }, "count": 10, "avg": 22.4 }
{ "_id": { "min": 45, "max": 82 }, "count": 10, "avg": 63.1 }

📌 Notes

📚 Related Tutorials

❓ FAQ

QIs the bucket count exact?
ANot always; few documents or skewed values can produce fewer buckets than requested.
QWhat does the granularity parameter do?
AIt snaps boundaries to canonical sequences like 1-2-5 or E12 for standard tick marks.
QShould I use $bucketAuto or $bucket?
AChoose $bucketAuto for even buckets without manual bounds; $bucket for custom boundaries.
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%

🙏 帮我们做得更好

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

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