0
0
MongoDBquery~30 mins

Computed pattern for pre-aggregation in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Computed Pattern for Pre-Aggregation in MongoDB
📖 Scenario: You work for a small online bookstore. You want to keep track of the total number of books sold per author to quickly show popular authors without counting every sale each time.
🎯 Goal: Build a MongoDB collection that stores book sales and a pre-aggregated collection that keeps the total sales per author updated using computed fields.
📋 What You'll Learn
Create a sales collection with documents containing book, author, and copies_sold fields.
Create a variable min_copies to filter sales with at least 5 copies sold.
Write an aggregation pipeline that sums copies_sold per author only for sales meeting the min_copies threshold.
Create a pre_aggregated_sales collection that stores the total copies sold per author.
💡 Why This Matters
🌍 Real World
Pre-aggregation helps websites and apps show summary data quickly without recalculating totals every time a user requests it.
💼 Career
Database developers and data engineers often create pre-aggregated collections or tables to improve performance and user experience.
Progress0 / 4 steps
1
DATA SETUP: Create the sales collection with sample sales data
Create a MongoDB collection called sales and insert these exact documents: { book: "Book A", author: "Author X", copies_sold: 10 }, { book: "Book B", author: "Author Y", copies_sold: 3 }, { book: "Book C", author: "Author X", copies_sold: 7 }, { book: "Book D", author: "Author Z", copies_sold: 2 }.
MongoDB
Need a hint?

Use db.sales.insertMany() with an array of documents.

2
CONFIGURATION: Define a variable min_copies to filter sales
Create a variable called min_copies and set it to 5. This will be used to filter sales with at least 5 copies sold.
MongoDB
Need a hint?

Use const min_copies = 5 to create the variable.

3
CORE LOGIC: Aggregate total copies sold per author with filtering
Write an aggregation pipeline on sales that filters documents where copies_sold is greater than or equal to min_copies, then groups by author and sums copies_sold as total_copies. Store the result in a variable called authorSales.
MongoDB
Need a hint?

Use $match to filter and $group to sum copies sold per author.

4
COMPLETION: Store the pre-aggregated results in pre_aggregated_sales collection
Insert the documents from authorSales into a new collection called pre_aggregated_sales.
MongoDB
Need a hint?

Use db.pre_aggregated_sales.insertMany(authorSales) to save the results.