Using $facet for Multiple Pipelines in MongoDB Aggregation
📖 Scenario: You work at a bookstore that keeps its sales data in a MongoDB collection called sales. Each document records a book sale with fields like title, genre, price, and copies_sold.The manager wants to see two things at once: the total revenue per genre and the top 3 best-selling books overall.
🎯 Goal: Build a MongoDB aggregation query using $facet to run two pipelines simultaneously:One pipeline calculates total revenue per genre.The other pipeline finds the top 3 best-selling books overall.
📋 What You'll Learn
Create a
sales collection with exact documents provided.Add a variable
minCopies set to 5 to filter popular books.Write an aggregation query using
$facet with two pipelines: revenueByGenre and topBooks.In
revenueByGenre, group by genre and sum total revenue (price * copies_sold).In
topBooks, filter books with copies_sold >= minCopies, sort by copies_sold descending, and limit to 3.Complete the aggregation query with the
db.sales.aggregate() call.💡 Why This Matters
🌍 Real World
Bookstores and retail businesses often need to analyze sales data in multiple ways simultaneously, such as revenue by category and best sellers.
💼 Career
Understanding $facet helps database developers and analysts write efficient queries that return multiple summaries in one request, saving time and resources.
Progress0 / 4 steps