How can I translate the following Sql query for Mongo?:
select a,b,sum(c) csum from coll wh
Until the Aggregation Framework is release in MongoDB 2.1, the call for group as in this answer, is rather slow, since it is using the JavaScript part of the DB.
You can use a faster approach for counting groups:
var res = [];
for( var cur_a = db.coll.distinct('a'); cur_a.hasNext(); ) {
var a = cur_a.next();
for( var cur_b = db.coll.distinct('b'); cur_b.hasNext(); ) {
var b = cur_b.next();
res.push({ 'a': a, 'b' : b 'count': db.coll.count({'a':a,'b':b})}
}
}
It will be faster if you have indexes on a and b
db.coll.ensureIndex({'a':1,'b':1})