MongoDB group by Functionalities

后端 未结 3 1053
不思量自难忘°
不思量自难忘° 2021-01-31 07:00

In MySQL

select a,b,count(1) as cnt from list group by a, b having cnt > 2;

I have to execute the group by function using h

3条回答
  •  滥情空心
    2021-01-31 07:16

    Depends on the number of your groups, you might find a simpler and faster solution than group or MapReduce by using distinct:

    var res = [];
    for( var cur_a = db.list.distinct('a'); cur_a.hasNext(); ) {
      var a = cur_a.next();
      for( var cur_b = db.list.distinct('b'); cur_b.hasNext(); ) {
        var b = cur_b.next();
        var cnt = db.list.count({'a':a,'b':b})
        if (cnt > 2)
          res.push({ 'a': a, 'b' : b 'cnt': cnt}
      }
    } 
    

    It will be faster if you have indexes on a and b

    db.list.ensureIndex({'a':1,'b':1})
    

提交回复
热议问题