Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by sum mongodb [duplicate]

Tags:

mongodb

This is my old MySQL query.

SELECT Count(`status`) as amt, `status` 
FROM (`users`) 
GROUP BY `status`

Which would return something like

+---------+----------+
| amt     | status   |
+---------+----------+
| 3       |        0 |
| 210     |        1 |
| 330     |        2 |
| 4233    |        3 | 
| 540085  |        4 |
+---------+----------+

This seems like the most basic of Mongo queries ever, but after many tries using $group then told to use $aggregate I still have no luck.

db.users.aggregate([ { 
    $group: { 
        _id: "$status", 
        amt: { $status: 1 }
    } 
} ] )

I thought this would work as selecting the status field, but since I included the $, it would count the amount of those grouped queries via the ` amt: { $status : 1 }

but my response is only

{ "result" : [ ], "ok" : 1 }

so it semi worked? but didn't return anything. I thought that is what the _id part was for.

I was following this example: http://docs.mongodb.org/manual/reference/aggregation/group/

like image 210
Connor Tumbleson Avatar asked Jul 28 '13 15:07

Connor Tumbleson


1 Answers

You're close, but you need to use a $sum operator to count the groupings:

db.users.aggregate([ { 
    $group: { 
        _id: "$status", 
        amt: { $sum: 1 }
    } 
} ] )
like image 157
JohnnyHK Avatar answered Oct 05 '22 13:10

JohnnyHK