0
0
MongoDBquery~30 mins

Why expressions matter in pipelines in MongoDB - See It in Action

Choose your learning style9 modes available
Why expressions matter in pipelines
📖 Scenario: You work for a small online bookstore. You have a collection of books documents in MongoDB. Each book has fields like title, author, price, and copies_sold. You want to analyze sales data using aggregation pipelines.
🎯 Goal: Build a MongoDB aggregation pipeline step-by-step that uses expressions to calculate total revenue per book and filter books with revenue above a certain amount.
📋 What You'll Learn
Create a books collection with exact documents
Add a variable for minimum revenue threshold
Use $addFields with an expression to calculate revenue
Use $match to filter books by revenue
💡 Why This Matters
🌍 Real World
Online stores and data analysts use aggregation pipelines to calculate sales metrics and filter products dynamically.
💼 Career
Understanding expressions in MongoDB pipelines is essential for backend developers and data engineers working with NoSQL databases.
Progress0 / 4 steps
1
DATA SETUP: Create the books collection with documents
Create a variable called books that is a list of three documents exactly as follows: {"title": "Learn MongoDB", "author": "Alice", "price": 30, "copies_sold": 100}, {"title": "Advanced MongoDB", "author": "Bob", "price": 45, "copies_sold": 50}, and {"title": "MongoDB for Beginners", "author": "Carol", "price": 25, "copies_sold": 200}.
MongoDB
Need a hint?

Use a Python list with dictionaries for each book document.

2
CONFIGURATION: Set a minimum revenue threshold
Create a variable called min_revenue and set it to 3000.
MongoDB
Need a hint?

Just assign the number 3000 to min_revenue.

3
CORE LOGIC: Use $addFields to calculate revenue per book
Create a variable called pipeline that is a list with one stage: { "$addFields": { "revenue": { "$multiply": ["$price", "$copies_sold"] } }}.
MongoDB
Need a hint?

Use $multiply inside $addFields to create a new field revenue.

4
COMPLETION: Add a $match stage to filter books by revenue
Add a second stage to the pipeline list: { "$match": { "revenue": { "$gt": min_revenue } } }.
MongoDB
Need a hint?

Add a $match stage after $addFields to filter books with revenue greater than min_revenue.