Mongodb group and sort

前端 未结 8 2117
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  -上瘾入骨i
    2020-12-09 16:18

    Adding to previous answers, if you want to sort on the sum (the result of the aggregate) instead of on the actual column, you can do this:

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

    This would be the equivalent of the following standard-SQL-ish syntax:

    select col_a, count(col_a) as b
    from table
    group by col_a
    order by b desc
    

提交回复
热议问题