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.