Home > Net >  Applying sum aggregator in $group with condition
Applying sum aggregator in $group with condition

Time:07-22

I need to use $group aggregation with condition. In the below example, $group separates documents into groups according to a Campaign_name and returns a sum of Basecount.

$group : {
              _id: "$Campaign_Name", 
              Basecount: { $sum: "$Basecount" }
         }

Here, I have different-different Campaign_name like winback, base, jca, etc in DB. Now, what I need to do is that if Camapign_name is Winback, then instead of taking sum of Basecount, I need take sum of another field Actcount i.e. instead of applying sum aggregator on Basecount, I need to apply it on a filed Actcount.

Thanks in advance.

CodePudding user response:

One option is using a $cond while doing the $group:

db.collection.aggregate([
  {
    $group: {
      _id: "$Campaign_Name",
      Basecount: {
        $sum: {
          $cond: [
            {
              $eq: [
                "$Campaign_Name",
                "Winback"
              ]
            },
            "$Actcount",
            "$Basecount"
          ]
        }
      }
    }
  }
])

See how it works on the playground example

  • Related