$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.
| Category | Grouping & Window |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $bucketAuto: { groupBy: <expression>, buckets: <positive integer>, output: { <field>: <accumulator> }, granularity: <granularity> } }
⚙️ Parameters
| groupBy | Expression that determines bucket membership. |
|---|---|
| buckets | Desired number of buckets; must be a positive integer. |
| output | Per-bucket accumulators, e.g. $avg or $sum. |
| granularity | Canonical 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
- buckets is a target; the real count may be lower with few documents or duplicate values
- Output _id is a { min, max } boundary object, half-open
- granularity snaps boundaries to canonical number sequences
🏷️ Related Tags
💡 Related Cases
📚 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.