0
0
MongoDBquery~30 mins

Why aggregation operators matter in MongoDB - See It in Action

Choose your learning style9 modes available
Why aggregation operators matter
📖 Scenario: You work at a small bookstore that keeps track of sales in a MongoDB database. You want to learn how to use aggregation operators to find useful information like total sales and average price per book.
🎯 Goal: Build a MongoDB aggregation pipeline step-by-step to calculate the total number of books sold and the average price of books sold.
📋 What You'll Learn
Create a collection called sales with documents containing book, price, and quantity fields.
Add a variable to hold the aggregation pipeline stages.
Use the $group aggregation operator to calculate total quantity sold and average price.
Complete the aggregation pipeline and assign it to a variable.
💡 Why This Matters
🌍 Real World
Aggregation operators help summarize and analyze data in databases, like calculating total sales or average prices in a bookstore.
💼 Career
Database developers and analysts use aggregation pipelines to generate reports and insights from large data collections efficiently.
Progress0 / 4 steps
1
DATA SETUP: Create the sales collection with sample documents
Create a variable called sales that is a list of three documents with these exact entries: { book: "MongoDB Basics", price: 20, quantity: 5 }, { book: "Advanced MongoDB", price: 35, quantity: 3 }, and { book: "MongoDB Aggregation", price: 25, quantity: 7 }.
MongoDB
Need a hint?

Use a Python list of dictionaries to represent the sales documents.

2
CONFIGURATION: Define the aggregation pipeline variable
Create a variable called pipeline and set it to an empty list [] to hold the aggregation stages.
MongoDB
Need a hint?

Just create an empty list called pipeline.

3
CORE LOGIC: Add a $group stage to calculate total quantity and average price
Add a dictionary to the pipeline list with a $group stage that groups all documents together (_id: null) and calculates totalQuantity as the sum of quantity and averagePrice as the average of price.
MongoDB
Need a hint?

Use $group with _id: null to aggregate all documents together.

4
COMPLETION: Assign the aggregation pipeline to a variable called aggregation_pipeline
Create a variable called aggregation_pipeline and assign it the value of the pipeline list.
MongoDB
Need a hint?

Just assign the existing pipeline list to aggregation_pipeline.