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