Conditional expressions ($cond, $switch) in MongoDB - Time & Space Complexity
When using conditional expressions like $cond or $switch in MongoDB, it's important to understand how their execution time changes as the data grows.
We want to know how the time to evaluate these conditions scales with the number of documents processed.
Analyze the time complexity of the following MongoDB aggregation snippet using $cond and $switch.
db.orders.aggregate([
{
$project: {
statusLabel: {
$switch: {
branches: [
{ case: { $eq: ["$status", "A"] }, then: "Active" },
{ case: { $eq: ["$status", "P"] }, then: "Pending" }
],
default: "Unknown"
}
}
}
}
])
This code assigns a label to each order based on its status field using conditional logic.
Look for repeated actions in the code.
- Primary operation: Evaluating the
$switchcondition for each document. - How many times: Once per document in the collection.
As the number of documents increases, the number of condition checks grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 condition checks |
| 100 | 100 condition checks |
| 1000 | 1000 condition checks |
Pattern observation: The work grows directly with the number of documents, so doubling documents doubles the checks.
Time Complexity: O(n)
This means the time to process grows linearly with the number of documents.
[X] Wrong: "Using $switch or $cond makes the query slower exponentially because of multiple conditions."
[OK] Correct: Each document is checked once, and conditions are evaluated in order, so the time grows linearly, not exponentially.
Understanding how conditional expressions scale helps you write efficient queries and explain your reasoning clearly in interviews.
"What if we added nested $cond expressions inside each branch? How would that affect the time complexity?"
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
