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
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
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
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
Hint
Use $set with $switch and branches to check ranges and assign categories.
Practice
(1/5)
1. What does the $cond operator do in a MongoDB aggregation pipeline?
easy
A. It chooses a value based on a simple if-else condition.
B. It sorts documents by a field value.
C. It groups documents by a key.
D. It removes duplicate documents.
Solution
Step 1: Understand the purpose of $cond
$cond is used to evaluate a condition and return one value if true, another if false, similar to if-else logic.
Step 2: Compare with other options
Sorting, grouping, and removing duplicates are done by other operators like $sort, $group, and $addToSet, not $cond.
Final Answer:
It chooses a value based on a simple if-else condition. -> Option A
Quick Check:
$cond = if-else logic [OK]
Hint: Remember $cond is like a simple if-else choice [OK]
Common Mistakes:
Confusing $cond with $group or $sort
Thinking $cond filters documents
Assuming $cond handles multiple cases like $switch
2. Which of the following is the correct syntax for using $cond in a MongoDB aggregation pipeline?
easy
A. { $cond: [ <condition>, <trueValue>, <falseValue> ] }
B. Missing default value in $switch returns null for unmatched cases.
C. Using $gt instead of $gte is invalid syntax.
D. The $project stage cannot use $switch.
Solution
Step 1: Check $switch structure
$switch requires branches; default is optional but without it returns null when no branch matches.
Step 2: Identify missing default
The expression lacks a default field, so if score <= 80, grade is null.
Final Answer:
Missing default value in $switch returns null for unmatched cases. -> Option B
Quick Check:
$switch missing default = null [OK]
Hint: Always include default in $switch to avoid errors [OK]
Common Mistakes:
Omitting default field in $switch
Thinking $gt is invalid syntax
Misplacing branches array
5. You want to categorize products by price using $switch in an aggregation pipeline. Prices below 20 are "Cheap", 20 to 50 are "Moderate", above 50 are "Expensive". Which of the following $switch expressions correctly implements this?