0
0
MongoDBquery~5 mins

Conditional expressions ($cond, $switch) in MongoDB

Choose your learning style9 modes available
Introduction

Conditional expressions let you choose values based on conditions, like making decisions in real life.

You want to assign a label based on a score, like 'pass' or 'fail'.
You need to set a discount rate depending on customer type.
You want to categorize ages into groups like 'child', 'adult', or 'senior'.
You want to replace missing values with a default.
You want to perform different calculations based on a field's value.
Syntax
MongoDB
1. $cond: { if: <condition>, then: <true-case>, else: <false-case> }

2. $switch: {
   branches: [
     { case: <condition1>, then: <result1> },
     { case: <condition2>, then: <result2> },
     ...
   ],
   default: <default-result>
}

$cond works like an if-else: if condition is true, return then, else return else.

$switch checks multiple conditions in order and returns the first matching then value, or default if none match.

Examples
Returns 'pass' if score is 60 or more, otherwise 'fail'.
MongoDB
{ $cond: { if: { $gte: ["$score", 60] }, then: "pass", else: "fail" } }
Classifies age into child, teen, adult, or senior.
MongoDB
{ $switch: {
  branches: [
    { case: { $lt: ["$age", 13] }, then: "child" },
    { case: { $lt: ["$age", 20] }, then: "teen" },
    { case: { $lt: ["$age", 65] }, then: "adult" }
  ],
  default: "senior"
} }
Sample Program

This query projects each student's name and score, then adds a 'result' field showing 'Passed' or 'Failed' based on score. It also adds a 'category' field classifying the score into 'Excellent', 'Good', 'Average', or 'Poor'.

MongoDB
db.students.aggregate([
  {
    $project: {
      name: 1,
      score: 1,
      result: {
        $cond: {
          if: { $gte: ["$score", 50] },
          then: "Passed",
          else: "Failed"
        }
      },
      category: {
        $switch: {
          branches: [
            { case: { $gte: ["$score", 90] }, then: "Excellent" },
            { case: { $gte: ["$score", 75] }, then: "Good" },
            { case: { $gte: ["$score", 50] }, then: "Average" }
          ],
          default: "Poor"
        }
      }
    }
  }
])
OutputSuccess
Important Notes

Use $cond for simple if-else decisions.

Use $switch when you have many conditions to check in order.

Conditions inside $cond and $switch use MongoDB query expressions like $gte, $lt, etc.

Summary

$cond and $switch help you pick values based on conditions.

$cond is like a simple if-else; $switch handles multiple cases.

They make your queries smarter by adding logic inside aggregation.