Search code examples
mongodbaggregation-frameworkcoalesce

Mongo how to write a CASE WHEN THEN ELSE


I'm trying to translate to mongo the following sql:

SELECT CASE WHEN COL_A IS NOT NULL THEN 'aaa' ELSE 'bbb' END AS FLAG, COL_B AS VALUE
FROM MY_TABLE

--- or, at least
SELECT coalesce(COL_A,'bbb') AS FLAG, COL_B AS VALUE
FROM MY_TABLE


/*sample json data*/
[
 { COL_A: "abc",
   COL_B: "123"
},{
 COL_B: "654"
},
{
COL_A: "zyx",
COL_B: "987"
}

]


/*expected_output*/
{
FLAG: "aaa", /*OR , at least, "abc"*/
VALUE: "123"
},{
FLAG: "bbb", 
VALUE: "654"
},{
FLAG: "aaa", /*or, at least, "zyx"*/
VALUE: "987"
}


In mongo I'm Here:

db.getCollection('MyTable').aggregate([    
{
  $project: 
     { 
       "_id": 0, 
       "FLAG" : { 
           $switch :{ 
                      branches: [ 
                                  {case: { "$COL_A": { $exists: true } then: "aaa" } }
                                ],
                       default: "bbb"
                     }
                 }, 

        "VALUE" : "$COL_B"
      }
}, 
{
    $limit:50
}

])

But it tells me unexpected identifier

EDIT:

Tested with $ifNull: I get an empty array as output instead of expected "bbb"

db.getCollection('MyTable').aggregate([    
{
  $project: 
     { 
       "_id": 0, 
       "FLAG" : {$ifNull: ["$COL_A", "bbb"] },
        "VALUE" : "$COL_B"
      }
}, 
{
    $limit:50
}

])

Solution

  • db.collection.aggregate([
      {
        $project: {
          "_id": 0,
          "FLAG": {
            $cond: [
              {
                $lte: [
                  "$COL_A",
                  null
                ]
              },
              "bbb",
              "aaa"
            ]
          },
          "VALUE": "$COL_B"
        }
      },
      {
        $limit: 50
      }
    ])
    

    To check if the value doesn't exist or is null use { $lte: ["$field", null] }

    enter image description here