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.
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}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With