Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb $cond inside $cond

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
          ]
        }
      }
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading