Home > database >  Mongodb $cond inside $cond
Mongodb $cond inside $cond

Time:07-22

I have to apply group by operation on Campaign_Name and then sum aggregator on a field which will be decided based on some condition. I am facing some syntax error in the below code sample:

   $group : {
              _id: "$Campaign_Name",
              Basecount: {
                $sum: {
                  $cond: [
                    { "Recharge_Flag_Overall": { $eq: "NA"} },
                    $cond: [
                      { "Plus_Orn" : { $eq: 0} },
                      "$Winback_Orn",
                      "$Plus_Orn"
                    ],
                    "$Basecount"
                  ]
                }
              }
            }

Now, the condition for the sum aggregator is that if Recharge_Flag_Overall value is "NA", then I need to check the value of Plus_Orn and, if it is 1, then I have to take the sum of Plus_Orn, else the sum of the field named Winback_Orn. Otherwise, if the Recharge_Flag_Overall value is not "NA", then simply, I have to take the sum of a field named Basecount

Note: Plus_Orn and Winback_Orn have only 0 or 1 as their values

CodePudding user response:

You are almost there, just have to correct the syntax of $eq operator,

  {
    $group: {
      _id: "$Campaign_Name",
      Basecount: {
        $sum: {
          $cond: [
            { $eq: ["$Recharge_Flag_Overall", "NA"] },
            {
              $cond: [
                { $eq: ["$Plus_Orn", 0] },
                "$Winback_Orn",
                "$Plus_Orn"
              ]
            },
            "$Basecount"
          ]
        }
      }
    }
  }
  • Related