$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.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $sortByCount: <expression> }
⚙️ Parameters
| grouping expression | Expression 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
- Output is fixed to _id and count fields
- Results are sorted by count descending
- An array field groups by the whole array; $unwind first to count per element
🏷️ Related Tags
💡 Related Cases
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.