Mongodb group and sort

前端 未结 8 2175
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 15:31

How can I translate the following Sql query for Mongo?:

select a,b,sum(c) csum from coll wh         


        
8条回答
  •  佛祖请我去吃肉
    2020-12-09 16:20

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

提交回复
热议问题