Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 815
purplecones Avatar asked Oct 16 '25 17:10

purplecones


1 Answers

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}}
])
like image 59
Sergey Berezovskiy Avatar answered Oct 18 '25 12:10

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!