fccoelho
fccoelho

Reputation: 6204

How to sort by count on Mongodb

I am doing a group-by operation, counting the number of entries on each group. Here is the code:

db.feeds.group({key:{link:1, 'subtitle_detail.base':1}, reduce:function(curr,result){
        result.count++
    },
    initial: {count: 0}
    })

This code returns an array. how do I modify the code so that the array is sorted in descending order, by count?

Upvotes: 0

Views: 5580

Answers (2)

TageS-K
TageS-K

Reputation: 1

If you have a large number of documents, sort will run out of memory. If that happens, you can tell the pipeline to sort on disk rather than in memory by adding the option allowDiskUse:

db.feeds.aggregate([
    {$group:{
        _id:{link:"$link", base:"$subtitle_detail.base"}, 
        count:{$sum:1}}},
    {$sort:{count:1}}
],
{allowDiskUse: True})

Upvotes: 0

Anand Jayabalan
Anand Jayabalan

Reputation: 12944

If you use the aggregation framework instead of group(), you can achieve this easily using an additional sort phase in the pipeline:

db.feeds.aggregate([
    {$group:{
        _id:{link:"$link", base:"$subtitle_detail.base"}, 
        count:{$sum:1}}},
    {$sort:{count:1}}
])

Upvotes: 2

Related Questions