$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