0
0
MongoDBquery~5 mins

Conditional expressions ($cond, $switch) in MongoDB - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the $cond operator do in MongoDB?
The $cond operator works like an if-then-else statement. It checks a condition and returns one value if true, and another if false.
Click to reveal answer
intermediate
How is the $switch operator different from $cond?
$switch lets you check multiple conditions in order, like a switch-case statement. It returns the value for the first true condition.
Click to reveal answer
beginner
Write a simple $cond expression to check if a field score is greater than 50 and return 'Pass' or 'Fail'.
{ $cond: { if: { $gt: ["$score", 50] }, then: "Pass", else: "Fail" } }
Click to reveal answer
intermediate
What happens if none of the conditions in $switch match and no default is provided?
If no conditions match and no default is set, $switch returns null.
Click to reveal answer
beginner
Why are conditional expressions useful in MongoDB aggregation?
They let you create new fields or change values based on conditions, making your data queries smarter and more flexible.
Click to reveal answer
Which operator in MongoDB acts like an if-then-else statement?
A$match
B$switch
C$cond
D$group
What does $switch do when multiple conditions are true?
AReturns the value of the last true condition
BReturns the value of the first true condition
CReturns all matching values
DReturns null
In a $cond expression, what does the else part represent?
AValue if condition is false
BThe field name
CThe condition to check
DValue if condition is true
If no conditions match in $switch and no default is set, what is returned?
Anull
BThe first condition's value
CAn error
DAn empty string
Which of these is a valid use of $cond?
ATo filter documents in a collection
BTo sort documents
CTo group documents by a field
DTo assign a value based on a condition
Explain how the $cond operator works in MongoDB and give a simple example.
Think of it like an if-else statement in programming.
You got /4 concepts.
    Describe the purpose of the $switch operator and how it handles multiple conditions.
    It is similar to switch-case statements in programming languages.
    You got /4 concepts.