MongoDB相当于SQL COUNT GROUP BY [英] MongoDB equivalent of SQL COUNT GROUP BY
问题描述
已阅读mongodb聚合和组文档,但仍然不清楚我。
Been reading the mongodb aggregation and group docs, however still unclear to me.
考虑使用文档的集合:
{
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 }
我想计算每个文档的数量a的值并按计数排序。
I want to count the number of documents for each value of a and sort by the count.
在关系样式中,它看起来像这样:
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 a ORDER BY total DESC;
有关如何
推荐答案
您首先 $ group
在 _id:$ a
与 $ sum:{1}
(这基本上是你对不同a的计数) c $ c> sort 。
You first $group
on _id:"$a"
with $sum:{1}
(this is basically your count on distinct a) then sort
on the sum.
这篇关于MongoDB相当于SQL COUNT GROUP BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!