$first and $last Accumulators in MongoDB Aggregation
📖 Scenario: You work at a bookstore that tracks sales data in a MongoDB collection. Each sale record includes the book title, the date of sale, and the price. You want to analyze the sales to find the first and last sale price for each book.
🎯 Goal: Build a MongoDB aggregation pipeline that groups sales by book title and uses the $first and $last accumulators to find the first and last sale price for each book.
📋 What You'll Learn
Create a collection called sales with documents containing title, date, and price fields.
Add a variable sortOrder to specify sorting by date ascending.
Write an aggregation pipeline that groups sales by title and uses $first and $last to get the first and last price per book.
Complete the aggregation pipeline by adding the $sort stage to order results by title.
💡 Why This Matters
🌍 Real World
Bookstores and retailers often analyze sales data to understand price changes over time for products.
💼 Career
Knowing how to use MongoDB aggregation with $first and $last is useful for data analysts and backend developers working with time-series or ordered data.
Progress0 / 4 steps
1
Create the sales collection with sample data
Create a variable called sales and assign it an array of documents with these exact entries: { title: "Book A", date: ISODate("2023-01-01"), price: 10 }, { title: "Book A", date: ISODate("2023-01-05"), price: 12 }, { title: "Book B", date: ISODate("2023-01-02"), price: 15 }, { title: "Book B", date: ISODate("2023-01-10"), price: 18 }
MongoDB
Hint
Use new Date("YYYY-MM-DD") to create date objects in JavaScript.
2
Add a sortOrder variable to sort by date ascending
Create a variable called sortOrder and assign it an object that sorts by date in ascending order using { date: 1 }.
MongoDB
Hint
Sorting by date ascending means using 1 as the value.
3
Write an aggregation pipeline using $first and $last
Create a variable called pipeline and assign it an array with these stages: first a { $sort: sortOrder } stage, then a { $group } stage that groups by title and uses $first to get the first price as firstPrice and $last to get the last price as lastPrice.
MongoDB
Hint
Remember to sort before grouping to get correct $first and $last values.
4
Add a $sort stage to order results by title
Add a final stage to the pipeline array that sorts the grouped results by _id in ascending order using { $sort: { _id: 1 } }.
MongoDB
Hint
Sorting by _id ascending orders the grouped results by book title.
Practice
(1/5)
1. What does the $first accumulator do in a MongoDB aggregation pipeline?
easy
A. It returns the last value of a specified field in each group.
B. It counts the number of documents in each group.
C. It sorts the documents in ascending order.
D. It returns the first value of a specified field in each group.
Solution
Step 1: Understand the role of $first
The $first accumulator returns the first value of a specified field from documents in a group.
Step 2: Differentiate from other accumulators
Unlike $last, which returns the last value, $first picks the earliest value based on the document order.
Final Answer:
It returns the first value of a specified field in each group. -> Option D
Quick Check:
$first = first value [OK]
Hint: Remember: $first picks earliest value in group [OK]
Common Mistakes:
Confusing $first with $last accumulator
Thinking $first sorts documents automatically
Assuming $first counts documents
2. Which of the following is the correct syntax to use $last in a MongoDB aggregation $group stage?
The $last accumulator must be used with a field path as a string, like "$item".
Step 2: Check syntax correctness
{ $group: { _id: "$category", lastItem: { $last: "$item" } } } correctly uses $last: "$item" inside $group. Options A and C have syntax errors, and B uses $first instead of $last.
You want to find each user's first and last event timestamps using the $first and $last accumulators. Which aggregation pipeline correctly achieves this?