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!
The MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.
The aggregation query takes ~80ms while the find query takes 0 or 1ms.
With aggregate + $match, you get a big monolithic BSON containing all matching documents. With find, you get a cursor to all matching documents. Then you can get each document one by one.
Booleans use less storage than an integer or string and avoid any unexpected side effects of comparison. For example, in a MongoDB find() query a string of "1" will not match a numeric value of 1 or a boolean value of true . If you want to store boolean values, definitely use a boolean type.
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.
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