Group by sum mongodb

2019-01-18 17:35发布

问题:

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/

回答1:

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

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


标签: mongodb