0
0
MongoDBquery~5 mins

Conditional expressions ($cond, $switch) in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Conditional expressions ($cond, $switch)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look for repeated actions in the code.

  • Primary operation: Evaluating the $switch condition for each document.
  • How many times: Once per document in the collection.
How Execution Grows With Input

As the number of documents increases, the number of condition checks grows proportionally.

Input Size (n)Approx. Operations
1010 condition checks
100100 condition checks
10001000 condition checks

Pattern observation: The work grows directly with the number of documents, so doubling documents doubles the checks.

Final Time Complexity

Time Complexity: O(n)

This means the time to process grows linearly with the number of documents.

Common Mistake

[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.

Interview Connect

Understanding how conditional expressions scale helps you write efficient queries and explain your reasoning clearly in interviews.

Self-Check

"What if we added nested $cond expressions inside each branch? How would that affect the time complexity?"