How to count booleans in MongoDB using an aggregation structure

Documents are stored with the following fields:

_id: NumberofChildren: Integer OwnsAHome: Boolean Income: Integer 

I need to use an aggregation structure to sort by the number of children, so the result looks something like this:

 Number of Children: 3 Number of People: some value, say 17 Number of People who own a home: some value less than 17 which is a sum of the number of true Booleans Average income: some value 

How would this be done in MongoDB with aggregation , especially with respect to counting the number of times Boolean OwnsAHome is true ?

Thanks!

+8
mongodb aggregation-framework
source share
2 answers

The $project phase is your friend in the pipeline, allowing you to create new fields that have different types and values ​​than the original fields.

Consider this projection, which uses $cond to use one value when something is true and another when it is false:

{$ project: {numWhoOwnHome: {$ cond: ["$ OwnsAHome", 1, 0]}}}

If you now run $group with {$sum : "$numWhoOwnHome"} , your result will be the number of people whose OwnSAHome is set to true.

+15
source share

I followed @eri's suggestion using $cond .

Given the data:

 campaign | flags.click | flags.removed c1 | true | false c1 | true | true c2 | false | false 

from:

 Contact.aggregate( [ { $group: { _id: "$campaign", countClick: { $sum: { $cond: ["$flags.click", 1, 0] } }, countRemoved: { $sum: { $cond: ["$flags.removed", 1, 0] } }, } } ] ).exec(); 

I will get the output:

 campaign | countClick | countRemoved c1 | 2 | 1 c2 | 0 | 0 
0
source share

All Articles