MongoDB $bucketAuto Stage

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $bucketAuto?

$bucketAuto is a MongoDB aggregation stage that builds a histogram with a number of buckets you choose. MongoDB computes the edges from the data—no boundaries array required.

Remember
$bucketAuto = "give me N bins; pick the edges"

{
  $bucketAuto: {
    groupBy: "$amount",
    buckets: 3,
    output: { count: { $sum: 1 } }
  }
}

_id → { min: <lower>, max: <upper> }
you choose bucket count, not edges
may return fewer buckets than requested
null → { min: null, max: null }

Fixed business ranges → use $bucket instead
UsePrefer
Auto edges, known bin count$bucketAuto
Fixed ranges you define$bucket
Exact key groups$group

How to Use $bucketAuto in MongoDB

Pick the field, choose how many bins you want, then optionally customize output.

  1. Optionally filter with $match (often drop nulls first).
  2. Set groupBy to the numeric field (e.g. "$amount").
  3. Set buckets to the number of bins (e.g. 3 or 5).
  4. Add output accumulators and optional granularity for rounder edges.
PieceRequired?Role
groupByYesExpression that picks the value to band
bucketsYesDesired number of bins (positive integer)
outputNoAccumulators per bin (default = count)
granularityNoPrefer rounder boundary series

Pseudocode

Pseudocode
for each document:
    v = evaluate(groupBy)
    collect values (nulls kept separate)

edges = autoCompute(values, buckets, granularity?)

for each document:
    assign to bucket where min <= v < max   // last max inclusive
    accumulate(bucket, document)

emit one summary per bucket:
  { _id: { min, max }, ...output fields }

Cheat Sheet

Keep these facts handy while building auto histograms.

TopicDetail
TypeAggregation stage
You providegroupBy + buckets count
MongoDB providesBoundary edges from the data
Bucket _id{ min, max } object
Fewer bins?Possible if data cannot fill N buckets
Nulls{ min: null, max: null }
vs $bucketAuto edges vs fixed boundaries

Live Preview

Simulate splitting the sample amounts into N bins (even document counts). Exact MongoDB edges can differ slightly.

Amounts used: 12, 35, 68, 95, 120, 185 (numeric sales only).

Result
buckets = 3
amounts = [12, 35, 68, 95, 120, 185]

{ _id: { min: 12, max: 68 }, count: 2 }
{ _id: { min: 68, max: 120 }, count: 2 }
{ _id: { min: 120, max: 185 }, count: 2 }

Worked Walkthrough — Three Bins

Six numeric amounts: 12, 35, 68, 95, 120, 185. Goal: ask for buckets: 3 and let MongoDB pick the edges.

Calculation
Input amounts (sorted):
  12, 35, 68, 95, 120, 185

Ask for 3 buckets → aim for even document counts
  (~2 documents per bin)

Illustrative result shape:
  { _id: { min: 12,  max: 68  }, count: 2 }  // 12, 35
  { _id: { min: 68,  max: 120 }, count: 2 }  // 68, 95
  { _id: { min: 120, max: 185 }, count: 2 }  // 120, 185

You chose N; MongoDB chose the edges.

MongoDB Examples

We use a small sales collection. First build an auto histogram, then add revenue totals per bin. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine six sales with different amounts, plus one gift-wrap row with null amount (we will filter it out before bucketing).

mongosh
db.sales.insertMany([
  { _id: 1, item: "Sticker pack", amount: 12, region: "East" },
  { _id: 2, item: "T-shirt", amount: 35, region: "West" },
  { _id: 3, item: "Hoodie", amount: 68, region: "East" },
  { _id: 4, item: "Laptop bag", amount: 95, region: "West" },
  { _id: 5, item: "Sneakers", amount: 120, region: "West" },
  { _id: 6, item: "Jacket", amount: 185, region: "East" },
  { _id: 7, item: "Gift wrap", amount: null, region: "East" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps seven documents in sales. Run find() to see them:

mongosh
db.sales.find()

Read the important fields like this:

FieldExamplePlain English
item"Hoodie"Product sold
amount12 … 185 / nullValue we will auto-bucket
region"East"Sales region (unused in these demos)

How It Works

  1. Insert once. insertMany adds seven sale documents to sales.
  2. Amounts span a range. Numeric values run from 12 to 185; one row is null.
  3. find() shows the same shape. Ready for $bucketAuto next.

Example 2 — Auto Histogram

Goal: keep only numeric amounts, then split them into 3 auto-computed bins and count each bin.

mongosh
db.sales.aggregate([
  { $match: { amount: { $type: "number" } } },
  {
    $bucketAuto: {
      groupBy: "$amount",
      buckets: 3,
      output: {
        count: { $sum: 1 }
      }
    }
  },
  { $sort: { "_id.min": 1 } }
]);

How It Works

  1. Filter nulls. $match keeps the six numeric amounts from Example 1.
  2. Ask for 3 bins. You set buckets: 3; MongoDB chooses the edges.
  3. Read _id.min / _id.max. Each summary row is one auto range plus count.
  4. Note: Exact edges can vary by version/data; the shape { min, max } stays the same.

Example 3 — Custom Output

Same auto bins, but also sum revenue and list item names in each bucket—just like accumulators in $group.

mongosh
db.sales.aggregate([
  { $match: { amount: { $type: "number" } } },
  {
    $bucketAuto: {
      groupBy: "$amount",
      buckets: 3,
      output: {
        count: { $sum: 1 },
        totalRevenue: { $sum: "$amount" },
        items: { $push: "$item" }
      }
    }
  },
  { $sort: { "_id.min": 1 } }
]);

How It Works

  1. Same auto assignment. Still three bins from the numeric sales.
  2. Add accumulators. $sum and $push summarize each bin.
  3. Dashboard-ready rows. Each bucket shows count, revenue, and item names.
  4. Easy check. Counts across bins should add up to 6 (all numeric sales).

Edge Cases & Pitfalls

Check these before using $bucketAuto in production pipelines.

count

You may get fewer than N buckets

If there are not enough distinct values, MongoDB can return fewer bins than buckets. Do not assume a fixed array length.

null

Nulls become their own bucket

Missing/null groupBy values land in { min: null, max: null }. Filter with $match when you want only numeric bins.

rules

Not for fixed business ranges

Tax brackets and age bands need exact edges. Use $bucket with boundaries for those rules.

edges

Edges can change when data changes

Because boundaries come from the current dataset, charts can shift after new inserts. Prefer $bucket when labels must stay stable.

Performance Notes

ApproachCostBest for
$bucketAutoScan + edge calc + assignExploratory histograms
$match then $bucketAutoFewer docs to scanLarge collections
$bucket with fixed edgesNo edge discoveryStable business bands

Auto edge discovery adds a little work versus fixed $bucket. Filter early with $match when only a subset should enter the histogram.

Key Takeaways

  • Role: ask for N bins; MongoDB picks the edges.
  • _id: { min, max } per auto range.
  • vs $bucket: exploration vs fixed business boundaries.
  • Nulls: filter first, or expect a null bucket.

One line: $bucketAuto answers “split this numeric field into about N bins for me.”

Frequently Asked Questions

$bucketAuto groups documents into a number of buckets you choose. MongoDB computes the edges from the data so documents are distributed across those bins—you do not pass a boundaries array.
groupBy (the expression to band) and buckets (a positive integer). output is optional; if omitted, MongoDB adds count: { $sum: 1 }. granularity is optional for rounder edges.
$bucket uses a single lower-bound _id (or a default label). $bucketAuto uses _id: { min: <value>, max: <value> } for each auto-computed range.
Use $bucketAuto for exploratory histograms when you know how many bins you want but not exact edges. Use $bucket when business rules fix the ranges (age bands, price tiers).
granularity nudges boundaries toward preferred round series (related to 1, 2, 5, 10, …). It can make chart labels cleaner, such as 0–50–100 instead of odd data-driven edges.
Null or missing values go into a bucket with _id: { min: null, max: null }. Filter them out with $match first if you do not want that bucket.

Next: $changeStream

Open a change stream to react to inserts, updates, and deletes in real time.

$changeStream tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful