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?"