Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Applying sum aggregator in $group with condition

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.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!