Reputation: 341
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
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
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
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