Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 738
jfeng92 Avatar asked Jun 19 '13 15:06

jfeng92


People also ask

Can we use count with aggregate function in MongoDB?

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.

Which is faster aggregate or find in MongoDB?

The aggregation query takes ~80ms while the find query takes 0 or 1ms.

What are the differences between using aggregate () and find ()? In MongoDB?

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.

Can you store booleans in MongoDB?

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.


1 Answers

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.

like image 110
Asya Kamsky Avatar answered Oct 27 '22 00:10

Asya Kamsky