按总和mongodb分组 [英] Group by sum mongodb

查看:83
本文介绍了按总和mongodb分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的旧MySQL查询.

This is my old MySQL query.

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

哪个会返回类似的内容

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

这似乎是有史以来最基本的Mongo查询,但是在尝试使用$group之后又被告知要使用$aggregate时,我仍然没有运气.

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 }
    } 
} ] )

我认为这可以作为选择状态字段的方法,但是由于我包括了$,因此可以通过`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 }

但我的回应只是

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

所以它半奏效了吗?但没有返回任何东西.我以为这就是_id部分的目的.

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

我正在关注以下示例: http://docs.mongodb.org/manual /reference/aggregation/group/

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

推荐答案

您已经很接近了,但是您需要使用$sum运算符来对分组进行计数:

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分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆