Discover how a few lines of conditional logic can save you hours of tedious work!
Why Conditional expressions ($cond, $switch) in MongoDB? - Purpose & Use Cases
Imagine you have a list of customer orders and you want to label each order as 'small', 'medium', or 'large' based on the order amount. Doing this by checking each order manually or writing many separate queries can be confusing and slow.
Manually checking each order's amount means writing repetitive code or running multiple queries. This is slow, easy to make mistakes, and hard to update if the rules change. It’s like sorting mail by hand instead of using a machine.
Using conditional expressions like $cond and $switch in MongoDB lets you write clear, simple rules inside one query. This automatically labels each order correctly without extra steps, saving time and avoiding errors.
if (order.amount < 50) { label = 'small'; } else if (order.amount < 100) { label = 'medium'; } else { label = 'large'; }
{ $switch: { branches: [ { case: { $lt: ["$amount", 50] }, then: "small" }, { case: { $lt: ["$amount", 100] }, then: "medium" } ], default: "large" } }This lets you create smart, flexible queries that adapt to your data’s conditions instantly, making your database work smarter for you.
A store can quickly categorize orders by size to offer discounts or shipping options, all within a single database query, without extra programming.
Manual checks are slow and error-prone.
$cond and $switch simplify conditional logic inside queries.
They help automate decisions directly in your data retrieval.
Practice
$cond operator do in a MongoDB aggregation pipeline?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 AQuick Check:
$cond = if-else logic [OK]
- Confusing $cond with $group or $sort
- Thinking $cond filters documents
- Assuming $cond handles multiple cases like $switch
$cond in a MongoDB aggregation pipeline?Solution
Step 1: Recall $cond syntax
The $cond operator uses an array with three elements: condition, true value, false value.Step 2: Check options
{ $cond: [ <condition>, <trueValue>, <falseValue> ] } matches the correct array syntax. Options A, C, and D use incorrect keys or object format.Final Answer:
{ $cond: [ <condition>, <trueValue>, <falseValue> ] } -> Option AQuick Check:
$cond syntax = array with 3 elements [OK]
- Using object keys like if/then/else instead of array
- Confusing $cond with $switch syntax
- Missing one of the three required elements
status for a document with score: 75?
{
$addFields: {
status: {
$switch: {
branches: [
{ case: { $gte: ["$score", 90] }, then: "Excellent" },
{ case: { $gte: ["$score", 70] }, then: "Good" },
{ case: { $gte: ["$score", 50] }, then: "Average" }
],
default: "Poor"
}
}
}
}Solution
Step 1: Evaluate $switch branches in order
The first branch checks if score >= 90 (75 >= 90? No). The second checks if score >= 70 (75 >= 70? Yes).Step 2: Determine matching branch and output
Since the second branch matches, the status is set to "Good". Later branches are ignored.Final Answer:
"Good" -> Option DQuick Check:
$switch picks first true case = "Good" [OK]
- Ignoring order of branches in $switch
- Choosing default instead of matching branch
- Confusing $gte logic
$switch:
{
$project: {
grade: {
$switch: {
branches: [
{ case: { $gt: ["$score", 90] }, then: "A" },
{ case: { $gt: ["$score", 80] }, then: "B" }
]
}
}
}
}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 BQuick Check:
$switch missing default = null [OK]
- Omitting default field in $switch
- Thinking $gt is invalid syntax
- Misplacing branches array
$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?Solution
Step 1: Analyze price ranges and conditions
Prices below 20 are "Cheap", 20 to 50 inclusive are "Moderate", above 50 are "Expensive". Conditions must be mutually exclusive and cover all cases.Step 2: Check each option's logic
{ $switch: { branches: [ { case: { $lt: ["$price", 20] }, then: "Cheap" }, { case: { $and: [ { $gte: ["$price", 20] }, { $lte: ["$price", 50] } ] }, then: "Moderate" }, { case: { $gt: ["$price", 50] }, then: "Expensive" } ], default: "Unknown" } } correctly uses $lt for below 20, $and with $gte and $lte for 20 to 50, and $gt for above 50. Others have overlapping or incorrect ranges.Final Answer:
{ $switch: { branches: [ { case: { $lt: ["$price", 20] }, then: "Cheap" }, { case: { $and: [ { $gte: ["$price", 20] }, { $lte: ["$price", 50] } ] }, then: "Moderate" }, { case: { $gt: ["$price", 50] }, then: "Expensive" } ], default: "Unknown" } } -> Option CQuick Check:
Use clear, non-overlapping conditions in $switch branches [OK]
- Overlapping ranges causing wrong category
- Using incorrect comparison operators
- Not covering all price values
Ready to prove it?
Pass the test and this pattern moves unknown
