Skip to content
LESSON 38 / 50Intermediateaggregation

$bucket and $bucketAuto: Histogram Categorization

Categorize numeric and temporal data into discrete histogram buckets using manual boundary ranges ($bucket) or automated equal-frequency percentiles ($bucketAuto).

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

1. Formal Definition & Architecture Intent

The $bucket stage categorizes incoming documents into groups (buckets) based on a specified expression and boundary values. The $bucketAuto stage automatically calculates boundary intervals to distribute documents evenly across a specified number of buckets (quantile/percentile bucketing).

2. Explain Like I'm 5 (Mental Model)

$bucket is like sorting coins into pre-labeled jars: 0-10 cents, 10-25 cents, 25-100 cents. $bucketAuto is asking a computer: "Here are 100 coins, sort them into 4 jars so each jar has exactly 25 coins."

3. Real-World Architecture Example

Analyzing user purchase price distribution into budget, mid-range, and premium brackets.

Sample BSON Documents:
Collection: db.orders
{
  "_id": "o1",
  "total": 75
}
Collection: db.orders
{
  "_id": "o2",
  "total": 320
}

$bucket groups orders into [0, 100), [100, 500), and [500, +inf).

4. MQL Implementation Steps

Step 1: Manual boundary bucketing
db.orders.aggregate([
  {
    $bucket: {
      groupBy: "$total",
      boundaries: [0, 100, 500, 1000],
      default: "Above 1000",
      output: {
        count: { $sum: 1 },
        avgSpend: { $avg: "$total" }
      }
    }
  }
]);
Boundaries must be sorted in ascending order.
Step 2: Automated quantile bucketing (4 equal quartiles)
db.orders.aggregate([
  {
    $bucketAuto: {
      groupBy: "$total",
      buckets: 4,
      output: { count: { $sum: 1 } }
    }
  }
]);
Calculates dynamic range boundaries automatically.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
$bucket BoundariesRequires at least 2 boundaries; each boundary must be strictly ascending (e.g. [0, 50, 100]).
Lower Bound InclusiveEach bucket includes the lower boundary and excludes the upper boundary: [lower, upper).

6. Deep Dive: Powering Analytical Histograms in Microseconds

Generating statistical histograms in relational databases requires complex CASE statements and repetitive range checks. $bucket executes this in a single indexed pass. If the groupBy field is indexed, WiredTiger reads the boundaries directly from the B-Tree, achieving sub-millisecond execution over millions of records.

// Output of $bucketAuto:
// { "_id": { "min": 10, "max": 45 }, "count": 250 },
// { "_id": { "min": 45, "max": 120 }, "count": 250 }
Production Warning: Ensure the groupBy field contains comparable data types.

7. Architectural Trade-offs

Advantages
  • •Generates statistical distributions and histograms natively inside the database
  • •$bucketAuto eliminates manual statistical range calculations for quantiles
  • •Integrates seamlessly inside $facet for search filtering
Disadvantages & Gotchas
  • •$bucket requires hardcoded domain knowledge to define sensible boundary numbers
  • •$bucketAuto can produce non-intuitive decimal boundaries on skewed data

8. Technical Interview Questions

Q1: What is the key difference between $bucket and $bucketAuto in MongoDB?

$bucket requires the developer to explicitly specify the boundary intervals (e.g. [0, 100, 500]) and a default bucket. $bucketAuto only takes the desired number of buckets (e.g. 5) and automatically calculates the boundary ranges so that documents are distributed as evenly as possible across the buckets.

9. Staff-Level Ready Answer

"$bucket partitions documents into custom user-defined range buckets ([lower, upper)). $bucketAuto automatically computes boundaries to partition data into N equal-frequency quantiles. Both optimize analytical histogram and price-filter generation."

10. Quick Knowledge Check

How does the $bucket stage treat boundary values for each range bucket?