$bucket (Bucket)

Last updated: 2026-10-09

$bucket (Bucket)

$bucket groups documents into buckets defined by an ascending boundaries array, emitting one { _id: lowerBound, count: N } document per bucket, with optional output accumulators. Documents outside all boundaries fall into the default bucket. Ideal for histograms and range statistics.

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

📝 Syntax

{ $bucket: { groupBy: <expression>, boundaries: [ <lowerBound>, ... ], default: <value>, output: { <field>: <accumulator> } } }

⚙️ Parameters

groupByExpression that determines which bucket a document falls into.
boundariesAscending bucket boundary array, at least two values.
defaultBucket name for documents outside all boundaries; omitted documents are dropped.
outputAccumulators computed per bucket, e.g. $avg or $sum.

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

▶ Example

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

// $bucket: bucket scores into ranges, average per bucket
db.scores.aggregate([
  { $bucket: {
    groupBy: '$score',
    boundaries: [0, 60, 80, 100],
    default: 'other',
    output: { avg: { $avg: '$score' } }
  } }
])

Output:

{ "_id": 0, "count": 12, "avg": 35.5 }
{ "_id": 60, "count": 20, "avg": 71.2 }

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $bucket and $bucketAuto?
A$bucket takes explicit boundaries; $bucketAuto splits buckets automatically for even counts.
QAre the ranges half-open?
AYes: values fall into [boundaries[i], boundaries[i+1]); the last boundary is an exclusive upper bound.
QCan the default bucket be omitted?
AYes; documents outside all buckets are then dropped.
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%

🙏 帮我们做得更好

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

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