MongoDB SELECT COUNT GROUP BY

后端 未结 7 2260
不知归路
不知归路 2020-11-22 15:24

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

7条回答
  •  难免孤独
    2020-11-22 15:37

    I need some extra operation based on the result of aggregate function. Finally I've found some solution for aggregate function and the operation based on the result in MongoDB. I've a collection Request with field request, source, status, requestDate.

    Single Field Group By & Count:

    db.Request.aggregate([
        {"$group" : {_id:"$source", count:{$sum:1}}}
    ])
    

    Multiple Fields Group By & Count:

    db.Request.aggregate([
        {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}}
    ])
    

    Multiple Fields Group By & Count with Sort using Field:

    db.Request.aggregate([
        {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
        {$sort:{"_id.source":1}}
    ])
    

    Multiple Fields Group By & Count with Sort using Count:

    db.Request.aggregate([
        {"$group" : {_id:{source:"$source",status:"$status"}, count:{$sum:1}}},
        {$sort:{"count":-1}}
    ])
    

提交回复
热议问题