0
0
MongoDBquery~10 mins

$first and $last accumulators in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $first and $last accumulators
Start with documents
Sort documents if needed
Group documents by key
$first picks first document's field
$last picks last document's field
Output grouped results with $first and $last values
Documents are sorted if needed, then grouped by a key. $first and $last pick the first and last values from each group after sorting.
Execution Sample
MongoDB
db.sales.aggregate([
  {$sort: {date: 1}},
  {$group: {
    _id: "$store",
    firstSale: {$first: "$amount"},
    lastSale: {$last: "$amount"}
  }}
])
This query sorts sales by date ascending, groups by store, then picks the first and last sale amounts per store.
Execution Table
StepInput DocumentGroup Key (_id)Sorted Order$first Value$last ValueAction
1{store: 'A', date: '2023-01-01', amount: 100}A1100100First document for group A, first and last both 100
2{store: 'A', date: '2023-01-05', amount: 150}A2100150Second document for A, last updated to 150
3{store: 'B', date: '2023-01-02', amount: 200}B1200200First document for B, first and last both 200
4{store: 'B', date: '2023-01-10', amount: 250}B2200250Second document for B, last updated to 250
5Aggregation complete--100150Group A final first and last values
6Aggregation complete--200250Group B final first and last values
💡 All documents processed, groups output with $first and $last values
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
Group A $firstnull100100100100100
Group A $lastnull100150150150150
Group B $firstnullnullnull200200200
Group B $lastnullnullnull200250250
Key Moments - 2 Insights
Why does $first not change after the first document in a group?
$first always takes the value from the first document in the sorted group, so after the first document, it remains unchanged as shown in rows 1 and 2 of the execution_table.
How does sorting affect $first and $last values?
Sorting determines the order of documents in each group. $first picks the first document after sorting, and $last picks the last. Without sorting, the order is unpredictable.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the $last value for group A?
A100
B150
Cnull
D200
💡 Hint
Check the $last Value column in row 2 of the execution_table.
At which step does group B first get a $first value assigned?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the Group Key and $first Value columns in the execution_table.
If the documents were not sorted by date, how would $first and $last behave?
AThey would pick values from documents in an unpredictable order.
BThey would still pick the earliest and latest dates correctly.
CThey would cause an error.
DThey would pick the same value for both $first and $last.
💡 Hint
Refer to the key_moments about sorting's effect on $first and $last.
Concept Snapshot
$first and $last accumulators in MongoDB aggregation:
- Use inside $group stage
- $first returns the first value in the group (after sorting)
- $last returns the last value in the group (after sorting)
- Sorting documents before grouping controls which values are first/last
- Useful to get earliest/latest values per group
Full Transcript
This visual execution trace shows how MongoDB's $first and $last accumulators work inside an aggregation pipeline. Documents are first sorted by date, then grouped by store. For each group, $first picks the amount from the earliest date document, and $last picks the amount from the latest date document. The execution table tracks each document processed, the group it belongs to, and how $first and $last values update. The variable tracker shows these values step-by-step. Key moments clarify why $first stays the same after the first document and how sorting affects results. The quiz tests understanding of these steps and the importance of sorting. This helps beginners see how $first and $last pick values from grouped documents in order.