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

264
Views
Group by count for boolean values in collection

If I have the follow data:

[{
  flagOne: true,
  flagTwo: true
},
{
  flagOne: true,
  flagTwo: false
},
{
  flagOne: true,
  flagTwo: false
},
{
  flagOne: true,
  flagTwo: true,
  flagThree: true
}]

Note that the flag may not be set and should be treated as false.

How do I get something like this aggregation result?

{
  flagOne: 4,
  flagTwo: 2,
  flagThree: 1
}

Basically, I would like to know the # of documents in my collection grouped by each of the boolean flags.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It doesn't matter whether flagThree exists, or it's equal to "tomato". Just count flags only if they have value true:

db.getCollection('so').aggregate([
    {
        $group: { 
            _id : 1,
            flagOne: {$sum: {$cond: [{$eq:["$flagOne", true]}, 1, 0]}},
            flagTwo: {$sum: {$cond: [{$eq:["$flagTwo", true]}, 1, 0]}},
            flagThree: {$sum: {$cond: [{$eq:["$flagThree", true]}, 1, 0]}},
        }
    },
    {$project: {_id:0}}
])

Output:

{
    "flagOne" : 4,
    "flagTwo" : 2,
    "flagThree" : 1
}

If you are completely sure all flags can have only boolean values, you can simplify query to

db.getCollection('so').aggregate([
    {
        $group: { 
            _id : 1,
            flagOne: {$sum: {$cond: ["$flagOne", 1, 0]}},
            flagTwo: {$sum: {$cond: ["$flagTwo", 1, 0]}},
            flagThree: {$sum: {$cond: ["$flagThree", 1, 0]}},
        }
    },
    {$project: {_id:0}}
])
over 4 years ago · Santiago Trujillo 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!