Articles → MONGODB → $Cond Operator In Mongodb

$Cond Operator In Mongodb






Purpose





Syntax


{
   $cond: {
      if: <boolean-expression>,
      then: <value-if-true>,
      else: <value-if-false>
   }
}




  1. If → A Boolean expression that evaluates to either true or false
  2. Then → The value to return if the if expression evaluates to true
  3. Else → The value to return if the if expression evaluates to false

Example




Picture showing the sample BSON document




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


Picture showing the output of cond operator in mongodb



Posted By  -  Karan Gupta
 
Posted On  -  Thursday, March 7, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250