Skip to content
LESSON 33 / 50Intermediateaggregation

$group Mechanics, Hash Tables & Accumulator Operators

The $group stage partitions documents into discrete buckets by an _id expression and computes aggregate metrics using mathematical and array accumulators.

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 $group stage separates documents into groups according to a specified group key (_id) and calculates metrics for each group using accumulator expressions ($sum, $avg, $min, $max, $push, $addToSet, $first, $last). The engine maintains an in-memory hash table where group keys point to accumulated state.

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

Think of sorting mail into pigeonholes by zip code. As letters arrive, you place them into the matching box and increment the counter written on the box.

3. Real-World Architecture Example

Computing total spend, average order value, and product categories purchased per customer.

Sample BSON Documents:
Collection: db.orders
{
  "user_id": "u1",
  "total": 150,
  "category": "Hardware"
}

$group by user_id calculates total spend via $sum and unique categories via $addToSet.

4. MQL Implementation Steps

Step 1: Aggregate financial summary by customer
db.orders.aggregate([
  {
    $group: {
      _id: "$user_id",
      totalSpent: { $sum: "$total" },
      avgOrderValue: { $avg: "$total" },
      orderCount: { $sum: 1 },
      categoriesBought: { $addToSet: "$category" } // Deduplicated array!
    }
  }
]);
_id: null groups all documents in the collection into a single global total.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
$addToSet vs $push$addToSet deduplicates items into a unique array; $push appends every item preserving duplicates.
_id: nullGrouping by null aggregates the entire dataset into a single overall summary row.

6. Deep Dive: In-Memory Hash Table & Memory Spill Over

During $group execution, MongoDB creates a dynamic in-memory hash table. Each unique _id key occupies a hash bucket. If the group key has high cardinality (e.g. grouping by unique UUID or email across 50M records), the hash table can quickly exceed 100MB of RAM. If allowDiskUse is false, the query aborts with an error.

// Global collection-wide sum:
db.orders.aggregate([
  { $group: { _id: null, grandTotal: { $sum: "$total" } } }
]);
Production Warning: Using $push on high-volume groups can produce output documents exceeding the 16MB document limit.

7. Architectural Trade-offs

Advantages
  • •Calculates multi-metric summaries ($sum, $avg, $min, $max) in a single database pass
  • •Supports array accumulation ($push, $addToSet) to aggregate child entities into parents
  • •Can group by complex composite expressions: { $group: { _id: { yr: "$year", mo: "$month" } } }
Disadvantages & Gotchas
  • •High-cardinality group keys consume significant memory, risking 100MB RAM exceptions
  • •$addToSet incurs hash-lookup overhead to deduplicate incoming array elements

8. Technical Interview Questions

Q1: What is the difference between $push and $addToSet accumulators in a $group stage?

$push appends every encountered value to an array in the output document, preserving duplicates and insertion order. $addToSet checks if the value already exists in the target array and only inserts it if it is unique, functioning as a mathematical set.

9. Staff-Level Ready Answer

"The $group stage separates documents into groups by an _id expression and calculates metrics using accumulator expressions. The engine maintains an in-memory hash table. $sum: 1 counts documents, $avg calculates arithmetic means, and $addToSet builds deduplicated arrays."

10. Quick Knowledge Check

How do you configure a $group stage to calculate the total sum of all documents in a collection into a single output row?