$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.
Aggregation Pipeline Multi-Stage Stream Stepper
Filter completed orders, aggregate total revenue by payment method, and sort highest first.
The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.
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.
{
"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
db.orders.aggregate([
{
$group: {
_id: "$user_id",
totalSpent: { $sum: "$total" },
avgOrderValue: { $avg: "$total" },
orderCount: { $sum: 1 },
categoriesBought: { $addToSet: "$category" } // Deduplicated array!
}
}
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| $addToSet vs $push | $addToSet deduplicates items into a unique array; $push appends every item preserving duplicates. |
| _id: null | Grouping 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" } } }
]);7. Architectural Trade-offs
- •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" } } }
- •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
$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?