MongoDB SELECT COUNT GROUP BY [英] MongoDB SELECT COUNT GROUP BY
本文介绍了MongoDB SELECT COUNT GROUP BY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在玩弄MongoDB试图弄清楚如何做一个简单的
I am playing around with MongoDB trying to figure out how to do a simple
SELECT province, COUNT(*) FROM contest GROUP BY province
但我似乎无法使用聚合函数计算出来。我可以使用一些非常奇怪的组语法来做到这一点。
But I can't seem to figure it out using the aggregate function. I can do it using some really weird group syntax
db.user.group({
"key": {
"province": true
},
"initial": {
"count": 0
},
"reduce": function(obj, prev) {
if (true != null) if (true instanceof Array) prev.count += true.length;
else prev.count++;
}
});
但是使用聚合函数有更简单/更快的方法吗?
But is there an easier/faster way using the aggregate function?
推荐答案
This would be the easier way to do it using aggregate
:
db.contest.aggregate([
{"$group" : {_id:"$province", count:{$sum:1}}}
])
这篇关于MongoDB SELECT COUNT GROUP BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文