Bird
Raised Fist0
MongoDBquery~20 mins

Conditional expressions ($cond, $switch) in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Conditional Expressions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of $cond in aggregation
Given the following MongoDB aggregation pipeline stage, what will be the value of the field status in the output document?

{ $project: { score: 85, status: { $cond: { if: { $gte: ["$score", 60] }, then: "Pass", else: "Fail" } } } }
A{"score": 85, "status": false}
B{"score": 85, "status": "Fail"}
C{"score": 85, "status": true}
D{"score": 85, "status": "Pass"}
Attempts:
2 left
💡 Hint
Think about whether the score is greater than or equal to 60.
❓ query_result
intermediate
2:00remaining
Using $switch for multiple conditions
What will be the value of the field grade after applying this aggregation stage?

{ $project: { score: 75, grade: { $switch: { branches: [ { case: { $gte: ["$score", 90] }, then: "A" }, { case: { $gte: ["$score", 80] }, then: "B" }, { case: { $gte: ["$score", 70] }, then: "C" } ], default: "F" } } } }
A{"score": 75, "grade": "A"}
B{"score": 75, "grade": "B"}
C{"score": 75, "grade": "C"}
D{"score": 75, "grade": "F"}
Attempts:
2 left
💡 Hint
Check the conditions in order from top to bottom.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in $cond usage
Which option contains a syntax error in the use of the $cond expression in MongoDB aggregation?
A{ $project: { result: { $cond: { condition: { $eq: ["$value", 10] }, then: "Ten", else: "Other" } } } }
B{ $project: { result: { $cond: { if: { $eq: ["$value", 10] }, then: "Ten", else: "Other" } } } }
C{ $project: { result: { $cond: [ { $eq: ["$value", 10] }, "Ten", "Other" ] } } }
D} } } } "rehtO" :esle ,"neT" :neht ,} ]01 ,"eulav$"[ :qe$ { :fi { :dnoc$ { :tluser { :tcejorp$ {
Attempts:
2 left
💡 Hint
Check the correct field name for the condition in $cond.
❓ optimization
advanced
2:00remaining
Optimizing $switch with overlapping conditions
Consider this $switch expression:

{ $switch: { branches: [ { case: { $gte: ["$score", 70] }, then: "Pass" }, { case: { $gte: ["$score", 90] }, then: "Excellent" } ], default: "Fail" } }

What is the problem with this $switch and how to fix it?
AThe $switch should use $cond instead for better performance.
BThe order of branches is wrong; the condition for 90 should come before 70 to avoid always matching 70 first.
CThe default value should be "Pass" instead of "Fail".
DThere is no problem; the $switch works as expected.
Attempts:
2 left
💡 Hint
Think about how $switch evaluates branches in order.
🧠 Conceptual
expert
2:00remaining
Behavior of $cond with missing else branch
What happens if you use $cond with only if and then fields, but omit the else field in MongoDB aggregation?
AIf the condition is false, the output field will be null.
BIf the condition is false, the output field will be missing from the document.
CMongoDB throws a syntax error because else is required.
DIf the condition is false, the output field will have the value false.
Attempts:
2 left
💡 Hint
Think about default behavior when else is not specified.

Practice

(1/5)
1. What does the $cond operator do in a MongoDB aggregation pipeline?
easy
A. It chooses a value based on a simple if-else condition.
B. It sorts documents by a field value.
C. It groups documents by a key.
D. It removes duplicate documents.

Solution

  1. 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.
  2. Step 2: Compare with other options

    Sorting, grouping, and removing duplicates are done by other operators like $sort, $group, and $addToSet, not $cond.
  3. Final Answer:

    It chooses a value based on a simple if-else condition. -> Option A
  4. Quick Check:

    $cond = if-else logic [OK]
Hint: Remember $cond is like a simple if-else choice [OK]
Common Mistakes:
  • Confusing $cond with $group or $sort
  • Thinking $cond filters documents
  • Assuming $cond handles multiple cases like $switch
2. Which of the following is the correct syntax for using $cond in a MongoDB aggregation pipeline?
easy
A. { $cond: [ <condition>, <trueValue>, <falseValue> ] }
B. { $cond: { if: <condition>, then: <trueValue>, else: <falseValue> } }
C. { $cond: { case: <condition>, then: <trueValue>, else: <falseValue> } }
D. { $cond: { when: <condition>, then: <trueValue>, else: <falseValue> } }

Solution

  1. Step 1: Recall $cond syntax

    The $cond operator uses an array with three elements: condition, true value, false value.
  2. Step 2: Check options

    { $cond: [ <condition>, <trueValue>, <falseValue> ] } matches the correct array syntax. Options A, C, and D use incorrect keys or object format.
  3. Final Answer:

    { $cond: [ <condition>, <trueValue>, <falseValue> ] } -> Option A
  4. Quick Check:

    $cond syntax = array with 3 elements [OK]
Hint: Use array syntax: condition, true, false for $cond [OK]
Common Mistakes:
  • Using object keys like if/then/else instead of array
  • Confusing $cond with $switch syntax
  • Missing one of the three required elements
3. Given the following aggregation stage, what will be the value of the field 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"
      }
    }
  }
}
medium
A. "Poor"
B. "Excellent"
C. "Average"
D. "Good"

Solution

  1. 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).
  2. Step 2: Determine matching branch and output

    Since the second branch matches, the status is set to "Good". Later branches are ignored.
  3. Final Answer:

    "Good" -> Option D
  4. Quick Check:

    $switch picks first true case = "Good" [OK]
Hint: Check $switch branches top to bottom, pick first true [OK]
Common Mistakes:
  • Ignoring order of branches in $switch
  • Choosing default instead of matching branch
  • Confusing $gte logic
4. Identify the issue in this aggregation expression using $switch:
{
  $project: {
    grade: {
      $switch: {
        branches: [
          { case: { $gt: ["$score", 90] }, then: "A" },
          { case: { $gt: ["$score", 80] }, then: "B" }
        ]
      }
    }
  }
}
medium
A. Branches array must be outside $switch object.
B. Missing default value in $switch returns null for unmatched cases.
C. Using $gt instead of $gte is invalid syntax.
D. The $project stage cannot use $switch.

Solution

  1. Step 1: Check $switch structure

    $switch requires branches; default is optional but without it returns null when no branch matches.
  2. Step 2: Identify missing default

    The expression lacks a default field, so if score <= 80, grade is null.
  3. Final Answer:

    Missing default value in $switch returns null for unmatched cases. -> Option B
  4. Quick Check:

    $switch missing default = null [OK]
Hint: Always include default in $switch to avoid errors [OK]
Common Mistakes:
  • Omitting default field in $switch
  • Thinking $gt is invalid syntax
  • Misplacing branches array
5. You want to categorize products by price using $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?
hard
A. { $switch: { branches: [ { case: { $gte: ["$price", 50] }, then: "Expensive" }, { case: { $gte: ["$price", 20] }, then: "Moderate" }, { case: { $lt: ["$price", 20] }, then: "Cheap" } ], default: "Unknown" } }
B. { $switch: { branches: [ { case: { $lte: ["$price", 20] }, then: "Cheap" }, { case: { $lt: ["$price", 50] }, then: "Moderate" }, { case: { $gte: ["$price", 50] }, then: "Expensive" } ], default: "Unknown" } }
C. { $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" } }
D. { $switch: { branches: [ { case: { $gte: ["$price", 50] }, then: "Expensive" }, { case: { $lte: ["$price", 20] }, then: "Cheap" }, { case: { $and: [ { $gt: ["$price", 20] }, { $lt: ["$price", 50] } ] }, then: "Moderate" } ], default: "Unknown" } }

Solution

  1. 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.
  2. 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.
  3. 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 C
  4. Quick Check:

    Use clear, non-overlapping conditions in $switch branches [OK]
Hint: Use clear, non-overlapping conditions with $and for ranges [OK]
Common Mistakes:
  • Overlapping ranges causing wrong category
  • Using incorrect comparison operators
  • Not covering all price values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard