I'm trying to group a set of documents and count them based on their value. For example
{ "_id" : 1, "item" : "abc1", "value" : "1" }
{ "_id" : 2, "item" : "abc1", "value" : "1" }
{ "_id" : 3, "item" : "abc1", "value" : "11" }
{ "_id" : 4, "item" : "abc1", "value" : "12" }
{ "_id" : 5, "item" : "xyz1", "value" : "2" }
Here I would like to group by "item" and get in return a count how many times the "value" is bigger than 10 and how many times smaller. So:
{ "item": "abc1", "countSmaller": 2, "countBigger": 1}
{ "item": "xyz1", "countSmaller": 1, "countBigger": 0}
A plain count could be easily achieved with $aggregate, but how can I achieve the above result?
You need to use the
$cond
operator. Here0
is value less than10
and1
value greater than10
. This doesn't exactly give you expected output. Perhaps someone will post better answer.Output:
You will need to convert your value to
integer
orfloat
What you need is the
$cond
operator of aggregation framework. One way to get what you want would be:Note: I have assumed
value
to numeric rather than String.Output: