0
0
MongoDBquery~10 mins

$group stage for aggregation in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $group stage for aggregation
Input Documents
Apply $group Stage
Group by _id Key
Aggregate Fields (sum, avg, etc.)
Output Grouped Documents
The $group stage collects input documents, groups them by a specified key (_id), and computes aggregate values for each group.
Execution Sample
MongoDB
db.sales.aggregate([
  { $group: { _id: "$item", totalQty: { $sum: "$quantity" } } }
])
Groups sales documents by item and sums the quantity for each item.
Execution Table
StepInput DocumentGroup Key (_id)Aggregation ActionGroup State After Step
1{ item: "apple", quantity: 5 }"apple"Create group 'apple', sum=5{ apple: 5 }
2{ item: "banana", quantity: 3 }"banana"Create group 'banana', sum=3{ apple: 5, banana: 3 }
3{ item: "apple", quantity: 2 }"apple"Add 2 to sum of 'apple'{ apple: 7, banana: 3 }
4{ item: "banana", quantity: 4 }"banana"Add 4 to sum of 'banana'{ apple: 7, banana: 7 }
5{ item: "orange", quantity: 1 }"orange"Create group 'orange', sum=1{ apple: 7, banana: 7, orange: 1 }
6No more documentsN/AAggregation complete{ apple: 7, banana: 7, orange: 1 }
💡 All input documents processed; aggregation groups finalized.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
Group 'apple' sum0557777
Group 'banana' sum0033777
Group 'orange' sum0000011
Key Moments - 3 Insights
Why does the $group stage use _id as the grouping key?
The _id field defines how documents are grouped. Each unique _id value creates a separate group. This is shown in the execution_table where each input document's item field becomes the _id key.
What happens when a new group key appears in the input documents?
A new group is created with initial aggregation values. For example, when 'orange' appears at step 5, a new group is created with sum starting at the quantity of that document.
How does the aggregation update existing groups?
When a document's group key matches an existing group, aggregation operators like $sum add to the current total. See step 3 where 'apple' sum increases from 5 to 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the sum for group 'banana' after step 4?
A7
B3
C4
D0
💡 Hint
Check the 'Group State After Step' column at step 4 for 'banana'.
At which step does the group 'orange' get created?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look for when 'orange' first appears in the 'Group Key (_id)' column.
If the third document had quantity 4 instead of 2, what would be the final sum for 'apple'?
A7
B9
C11
D5
💡 Hint
Add the changed quantity to the previous sum for 'apple' from the variable_tracker.
Concept Snapshot
$group stage syntax:
{ $group: { _id: <grouping_key>, <field>: { <accumulator>: <expression> } } }
Groups documents by _id and applies accumulators like $sum, $avg.
Each unique _id value creates one output document.
Useful for summarizing data by categories.
Full Transcript
The $group stage in MongoDB aggregation groups input documents by a specified key called _id. Each unique _id value forms a group. For each group, accumulator operators like $sum add values from documents in that group. The execution table shows step-by-step how documents are processed: new groups are created when a new _id appears, and existing groups update their totals. Variables track sums for each group after each step. Key moments clarify why _id is used, how new groups form, and how aggregation updates work. The visual quiz tests understanding of sums at steps, group creation timing, and effects of changing input values. The snapshot summarizes syntax and behavior for quick reference.