Conditional expressions let you choose values based on conditions, like making decisions in real life.
Conditional expressions ($cond, $switch) in MongoDB
1. $cond: { if: <condition>, then: <true-case>, else: <false-case> } 2. $switch: { branches: [ { case: <condition1>, then: <result1> }, { case: <condition2>, then: <result2> }, ... ], default: <default-result> }
$cond works like an if-else: if condition is true, return then, else return else.
$switch checks multiple conditions in order and returns the first matching then value, or default if none match.
{ $cond: { if: { $gte: ["$score", 60] }, then: "pass", else: "fail" } }{ $switch: {
branches: [
{ case: { $lt: ["$age", 13] }, then: "child" },
{ case: { $lt: ["$age", 20] }, then: "teen" },
{ case: { $lt: ["$age", 65] }, then: "adult" }
],
default: "senior"
} }This query projects each student's name and score, then adds a 'result' field showing 'Passed' or 'Failed' based on score. It also adds a 'category' field classifying the score into 'Excellent', 'Good', 'Average', or 'Poor'.
db.students.aggregate([
{
$project: {
name: 1,
score: 1,
result: {
$cond: {
if: { $gte: ["$score", 50] },
then: "Passed",
else: "Failed"
}
},
category: {
$switch: {
branches: [
{ case: { $gte: ["$score", 90] }, then: "Excellent" },
{ case: { $gte: ["$score", 75] }, then: "Good" },
{ case: { $gte: ["$score", 50] }, then: "Average" }
],
default: "Poor"
}
}
}
}
])Use $cond for simple if-else decisions.
Use $switch when you have many conditions to check in order.
Conditions inside $cond and $switch use MongoDB query expressions like $gte, $lt, etc.
$cond and $switch help you pick values based on conditions.
$cond is like a simple if-else; $switch handles multiple cases.
They make your queries smarter by adding logic inside aggregation.
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
