The $bucketAuto stage builds a histogram automatically—you pick how many bins (buckets) and which field (groupBy); MongoDB figures out the range edges from your data.
01
Auto edges
No boundaries array.
02
buckets count
How many bins to create.
03
_id min/max
Range object per bucket.
04
granularity
Round-number boundaries.
05
Custom output
count, avg, sum, $push.
06
vs $bucket
Auto vs fixed ranges.
Fundamentals
Definition and Usage
$bucketAuto is an aggregation stage that divides documents into a fixed number of numeric buckets based on a groupBy expression. MongoDB inspects the minimum and maximum values in the pipeline input, then creates approximately equal-width intervals.
💡
Beginner tip
Each result document’s _id is an object: { min: 0, max: 250 } means “values from 0 up to (but not including) 250.” The last bucket’s max may equal the data maximum.
Use $bucketAuto for quick distribution charts—order amounts, response times, test scores—when you do not have predefined tiers. When ranges are fixed by policy, use $bucket instead. Add $avg or $sum inside output for richer stats.
granularity tells MongoDB to prefer boundary values that are multiples of round numbers—ideal when chart axes should read 0, 50, 100 instead of arbitrary splits.
Both stages produce histogram-style summaries. Choose $bucketAuto for discovery dashboards; choose $bucket when compliance or marketing defines exact breakpoints.
Compare
📋 $bucketAuto vs related stages
Stage
Effect
Best for
$bucketAuto
Auto-compute ~N equal-width numeric bins
Exploratory histograms, unknown data range
$bucket
Group by boundaries you define
Fixed tiers, tax brackets, SLA bands
$group
Group by any _id expression
Categories, dates, non-numeric keys
$sortByCount
Count documents per distinct field value
Top categories, not numeric ranges
$facet
Multiple sub-pipelines at once
Several bucket views in one query
🧠 How $bucketAuto Works
1
Scan groupBy values
MongoDB evaluates groupBy on all input documents and finds the overall min and max (excluding null handling rules).
Scan
2
Compute boundaries
The range is divided into buckets segments. Optional granularity rounds edges to tidy numbers.
Split
3
Assign & aggregate
Each document lands in a bin; output accumulators update per bucket.
Aggregate
=
⚙️
Histogram rows out
One document per bucket with _id: { min, max } and your stats.
Important
📝 Notes
Bucket count may be fewer thanbuckets if MongoDB merges empty adjacent bins.
Null/missing groupBy values go to _id: { min: null, max: null }—filter with $match if unwanted.
All documents in the pipeline input affect boundary calculation—even outliers widen the range.
Sort by "_id.min" for left-to-right chart order.
granularity is a hint—MongoDB picks the nearest friendly multiple, not an exact guarantee on every dataset.
$bucketAuto is the fastest path to a numeric histogram when you know how many bins you want but not where to draw the lines. Set groupBy and buckets, enrich with output, and add granularity for readable chart axes.
Switch to $bucket when ranges are fixed by business rules. Filter outliers or nulls before bucketing for cleaner results.
Use $match first to drop nulls, test data, or extreme outliers
Start with 4–10 buckets for readable charts, then tune
Add granularity when axis labels should be round numbers
Sort by _id.min ascending before sending to a chart library
Pair with $project to add friendly labels from min/max
❌ Don’t
Use $bucketAuto when legal/compliance defines exact tier edges
Assume exact bucket count always equals buckets—empty bins may merge
Bucket categorical strings—use $group or $sortByCount
Ignore the null bucket when groupBy can be missing
Expect identical boundaries on every run if input data changes frequently
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $bucketAuto
Use these points whenever you build data-driven histograms.
5
Core concepts
⚙️01
Auto edges
No boundaries array.
Basics
📊02
buckets: N
Target bin count.
Required
📦03
_id min/max
Range per bucket.
Output
🔢04
granularity
Round boundaries.
Polish
🛠05
vs $bucket
Auto vs fixed tiers.
Choose
❓ Frequently Asked Questions
$bucketAuto groups documents into a specified number of buckets (histogram bins) without you defining boundary values. MongoDB scans groupBy values in the input, computes min/max, and splits the range into roughly equal-width intervals.
groupBy (expression such as "$amount") and buckets (positive integer—how many bins you want). output is optional; if omitted, MongoDB adds count: { $sum: 1 }. granularity and facet are optional advanced options.
$bucket uses _id as a single lower-bound number (or default label). $bucketAuto uses _id: { min: <value>, max: <value> }—an object showing the inclusive min and exclusive max of each auto-computed range.
Use $bucketAuto for exploratory charts when you know how many bins you want but not exact edges—sales spread, latency distribution, score histograms. Use $bucket when business rules fix the ranges (tax brackets, age bands 0–18).
granularity nudges bucket boundaries toward round numbers from MongoDB's preferred series (1, 2, 5, 10, 20, 25, 50, 100…). Example: granularity: 100 may produce 0–100, 100–200 instead of 0–87, 87–174.
Documents where groupBy is null or missing are placed in a bucket whose _id is { min: null, max: null }. Filter with $match before bucketing if you want to exclude them.
Did you know?
The optional facet field in $bucketAuto lets you compute separate auto histograms for each distinct facet value in one stage—useful for per-region or per-category distribution charts. See the official $bucketAuto docs.