0
0
MongoDBquery~30 mins

Conditional expressions ($cond, $switch) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Conditional Expressions ($cond, $switch) in MongoDB Aggregation
📖 Scenario: You work at a bookstore that stores sales data in a MongoDB collection. You want to categorize each sale based on the number of books sold.
🎯 Goal: Build an aggregation pipeline that uses MongoDB's $cond and $switch conditional expressions to add a new field saleCategory to each document. This field will describe the sale size as 'Small', 'Medium', or 'Large' based on the number of books sold.
📋 What You'll Learn
Create a collection named sales with documents containing _id and booksSold fields.
Define a threshold variable mediumThreshold to separate small and medium sales.
Use the $cond expression to classify sales as 'Small' or 'Medium/Large'.
Use the $switch expression to further classify 'Medium/Large' sales into 'Medium' or 'Large'.
Add the final saleCategory field to each document in the aggregation result.
💡 Why This Matters
🌍 Real World
Conditional expressions in MongoDB aggregation pipelines help categorize and transform data dynamically, useful in sales analysis, reporting, and decision-making.
💼 Career
Understanding <code>$cond</code> and <code>$switch</code> is essential for data analysts and backend developers working with MongoDB to create flexible and powerful data queries.
Progress0 / 4 steps
1
Create the sales collection with sample data
Create a MongoDB collection named sales and insert these exact documents: { _id: 1, booksSold: 3 }, { _id: 2, booksSold: 7 }, { _id: 3, booksSold: 12 }.
MongoDB
Need a hint?

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

2
Define the medium sales threshold
Create a variable named mediumThreshold and set it to 5 to separate small and medium sales.
MongoDB
Need a hint?

Use const mediumThreshold = 5 to define the threshold.

3
Use $cond to classify sales as Small or Medium/Large
Write an aggregation pipeline that uses $cond to add a field saleCategory with value 'Small' if booksSold is less than mediumThreshold, otherwise 'Medium/Large'. Use $addFields stage.
MongoDB
Need a hint?

Use $addFields with $cond to check if booksSold is less than mediumThreshold.

4
Use $switch to refine Medium/Large classification
Extend the aggregation pipeline by adding a $set stage that uses $switch to update saleCategory: if booksSold is between mediumThreshold and 10 inclusive, set to 'Medium'; if greater than 10, set to 'Large'; otherwise keep the existing saleCategory.
MongoDB
Need a hint?

Use $set with $switch and branches to check ranges and assign categories.