Add a case i mongo db query

[{"$group":{"_id":{"isActive":"$isActive"},"count":{"$sum":1}}},
 {"$sort":{"_id":1}},
 {"$project":{"_id":false,"isActive":"$_id.isActive","count":true}},
 {"$sort":{"isActive":1}}]

The output is


I want to update such that for true, it should be active and for false it should be inactive. Can you help me add a case statement?

Hi @Anum_Hassan ,

Sure with the $switch operator you can do that:

[{$group: {
  "_id": {
    "isActive": "$isActive"
  },
  "count": {
    "$sum": 1
  }
}}, {$sort: {
  "_id": 1
}}, {$project: {
  "_id": false,
  "status":{
          $switch:
            {
              branches: [
                {
                  case: { $eq : [ "$_id.isActive", true] },
                  then: "active"
                },
                {
                  case: { $eq : [ "$_id.isActive", false] },
                  then: "inactive"
                }
              ],
              default: "No status"
            }
         }
      ,
  "count": true
}}, {$sort: {
  "isActive": 1
}}]

Thanks,
Pavel

1 Like

Thanks, @Pavel_Duchovny. This works. Can you help me add a start-to-end date clause in this query?

@Anum_Hassan ,

Not sure what do you mean? Do you need to add a $match for dates on the beginning of this pipeline?

thanks,
Pavel