MongoDB SELECT COUNT GROUP BY

后端 未结 7 2179
不知归路
不知归路 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:32

    This type of query worked for me:

     db.events.aggregate({$group: {_id : "$date", number:  { $sum : 1} }} )
    

    See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/

    0 讨论(0)
  • 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}}
    ])
    
    0 讨论(0)
  • 2020-11-22 15:38

    If you need multiple columns to group by, follow this model. Here I am conducting a count by status and type:

      db.BusinessProcess.aggregate({
        "$group": {
            _id: {
                status: "$status",
                type: "$type"
            },
            count: {
                $sum: 1
            }
        }
       })
    
    0 讨论(0)
  • 2020-11-22 15:42

    Starting in MongoDB 3.4, you can use the $sortByCount aggregation.

    Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.

    https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/

    For example:

    db.contest.aggregate([
        { $sortByCount: "$province" }
    ]);
    
    0 讨论(0)
  • 2020-11-22 15:44

    Mongo shell command that worked for me:

    db.getCollection(<collection_name>).aggregate([{"$match": {'<key>': '<value to match>'}}, {"$group": {'_id': {'<group_by_attribute>': "$group_by_attribute"}}}])
    
    0 讨论(0)
  • 2020-11-22 15:45

    This would be the easier way to do it using aggregate:

    db.contest.aggregate([
        {"$group" : {_id:"$province", count:{$sum:1}}}
    ])
    
    0 讨论(0)
提交回复
热议问题