What is the difference between $sortByCount and $group

Hi,

I am right now at chapter4 lecture 2.
I have come across ‘$sortByCount’ but I don’t understand what difference does it make in real with $group

For Example:

Using $sortByCount:

db.companies.aggregate([{
$match: {
$text: {
$search: ‘network’
}
}
}, {
$sortByCount: ‘$category_code’
}])

Using $group:

db.companies.aggregate([{
$match: {
$text: {
$search: ‘network’
}
}
}, {
$group: {
_id: ‘$category_code’,
count: { $sum: 1 }
}
},
{
$sort: {
count: -1
}
}])

I simply feel that if I am using ‘$group’ I have to add some more lines of code to achieve the result.

What is the difference between ‘$group’ and ‘$sortByCount’?

$sortByCount is somewhat a subset of $group in that it only returns a count, but in addition, it sorts the result. $group does more than counting… it can sum, avg etc… but you will need another stage to sort.

If all you want to do is return a count of documents, use $count.
If you want a count of documents and you want the results sorted, use $sortByCount
If you want to do an a different aggregation other than counting, use $group.

3 Likes

Hey @jchakrad

Good answer from @007_jb

And I believe, since this is a common operation, is the reason MongoDB introduced the $sortByCount expression

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

Each output document contains two fields: an _id field containing the distinct grouping value, and a count field containing the number of documents belonging to that grouping or category.

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

Each output document contains two fields: an _id field containing the distinct grouping value, and a count field containing the number of documents belonging to that grouping or category.

The documents are sorted by count in descending order.

It seems like $sortByCount does a sort in descending order what if I want an ascending order ?

You use group and sort. They introduced sortByCount in 3.4. Probably because it was a frequent use case and by doing a special operator they could optimise it.

2 Likes