Skip to main content

Mongodb if else statement

According to MongoDb docs, $cond "evaluates a Boolean expression to return one of the two specified return expressions".
Syntax:

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

OR

{$cond: [<expression>, <true>, <false>] }


Example for MongoDb if else statement

db.customers.aggregate(
   [{
         $project:
           {
             C_Id: 1,
             C_Type:
               {
                 $cond: {
                                    if: { $gte: [ "$C_Id", "IT "] },
                                                then: "N_Customer",
                                                else: "VIP_Customer"
                                       }
               }
           }
    }]
)

For more detail, go to