Articles → MONGODB → $Cond Operator In Mongodb
$Cond Operator In Mongodb
Purpose
Syntax
{
$cond: {
if: <boolean-expression>,
then: <value-if-true>,
else: <value-if-false>
}
}
- If → A Boolean expression that evaluates to either true or false
- Then → The value to return if the if expression evaluates to true
- Else → The value to return if the if expression evaluates to false
Example
db.Students.aggregate([
{
$project: {
_id: 1, // Keep the original _id field, or specify other fields if needed
grade: {
$cond: {
if: { $gte: ["$score", 90] },
then: "A",
else: {
$cond: {
if: { $gte: ["$score", 80] },
then: "B",
else: "C"
}
}
}
}
}
}
])
Output