0
0
MongoDBquery~30 mins

$first and $last accumulators in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$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
Need a 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
Need a 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
Need a 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
Need a hint?

Sorting by _id ascending orders the grouped results by book title.