$sortByCount (Sort By Count)

Last updated: 2026-10-09

$sortByCount (Sort By Count)

$sortByCount is shorthand for $group plus $sort: it groups by an expression's value, counts documents per group, and emits { _id: value, count: N } sorted by count descending. Perfect for word frequency and category rankings. Equivalent to $group with $sum: 1 followed by $sort on count descending.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $sortByCount: <expression> }

⚙️ Parameters

grouping expressionExpression determining the group key; a field reference or computed expression.

Returns:{ _id, count } document stream ordered by count descending

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $sortByCount: count reviews by rating
db.reviews.aggregate([
  { $sortByCount: '$rating' }
])

Output:

{ "_id": 5, "count": 42 }
{ "_id": 4, "count": 31 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $sortByCount and $group?
A$sortByCount is shorthand for $group plus $sort, fixed to _id/count output ordered by count descending.
QCan the result be sorted ascending?
ANot directly; write a plain $group plus $sort when you need another order.
QCan it group by multiple fields?
APass a document expression referencing several fields as the group key.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏