简体   繁体   English

MongoDB相当于SQL COUNT GROUP BY

[英]MongoDB equivalent of SQL COUNT GROUP BY

Been reading the mongodb aggregation and group docs, however still unclear to me. 一直在阅读mongodb聚合和组文档,但是我仍然不清楚。

Consider the collection with docs: 考虑文档集合:

{ a : 1, b : 0 } {a:1,b:0}

{ a : 1, b : 1 } {a:1,b:1}

{ a : 2, b : 2 } {a:2,b:2}

{ a : 3, b : 3 } {a:3,b:3}

I want to count the number of documents for each value of a and sort by the count. 我想计算a的每个值的文档数,然后按计数排序。

In the relational style it would look something like this: 在关系样式中,它看起来像这样:

SELECT COUNT(distinct b) AS total FROM example_table GROUP BY a ORDER BY total DESC; SELECT COUNT(distinct b)AS total from example_table GROUP BY ORDER BY total DESC;

Any suggestions on how to do this in mongo? 有关如何在mongo中执行此操作的任何建议?

您首先用$sum:{1}_id:"$a"上的$group (这基本上是您对不同a的计数),然后sort总和进行sort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM