jfeng92
jfeng92

Reputation: 341

How to count Booleans in MongoDB with aggregation framework

Documents are stored with the following fields:

_id:
NumberofChildren: Integer
OwnsAHome: Boolean
Income: Integer

I need to use the aggregation framework to sort by number of children so the output is 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 I do this in MongoDB with aggregation , especially in regards to counting the number of times the Boolean OwnsAHome, is true?

Thanks!

Upvotes: 23

Views: 11654

Answers (3)

damien
damien

Reputation: 11

(as a follow up to this answer) You may even use $toInt instead of $cond

db.Contact.aggregate(
    [
        {
            $group: {
                _id: "$campaign",
                countClick: {
                    $sum: { $toInt: "$flags.click" }
                },
                countRemoved: {
                    $sum: { $toInt: "$flags.removed" }
                },
            }
        }
    ]
)

Upvotes: 1

Manuel Spigolon
Manuel Spigolon

Reputation: 12880

I followed the @eri suggestion using $cond.

Given the data:

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

with:

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

Upvotes: 22

Asya Kamsky
Asya Kamsky

Reputation: 42352

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

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

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

If you now do a $group with {$sum : "$numWhoOwnHome"} your result will be the number of people who had OwnsAHome set to true.

Upvotes: 19

Related Questions