Skip to main content

Command Palette

Search for a command to run...

How to Find the Most Frequent Values in MongoDB Using $sortByCount

Learn how to quickly group and sort your data by frequency using MongoDB’s $sortByCount stage—with real-world examples and use cases.

Published
4 min read
How to Find the Most Frequent Values in MongoDB Using $sortByCount
D
I’m a software engineer who loves creating strong and reliable systems that help ideas work smoothly behind the scenes. I enjoy solving real problems and building solutions that make technology simple and useful for everyone. Along the way, I share what I learn through blogs and tutorials to help others understand backend development better. My goal is to make the tech world easier to explore and more helpful for all. Let’s build, learn, and grow together.

Hey devs! 👋

Ever wanted to quickly find what appears the most in your data? MongoDB’s $sortByCount stage makes it effortless! 📊

It combines grouping and sorting in one powerful step, letting you uncover the most frequent values in any field—whether it’s top search queries, common error codes, or most used tags.

Perfect for dashboards, analytics, or just exploring patterns in your data. Let’s dive in and see it in action! 🚀


In the world of data, knowing what appears the most is often more valuable than knowing just what exists.

Whether you're analyzing the most purchased product, the most active user, or the most common error type in logs—MongoDB’s $sortByCount aggregation stage gives you exactly that in one clean step.

If you’ve ever wanted to group your data by a field and instantly sort it by frequency, $sortByCount is your new best friend.


What is $sortByCount in MongoDB? 📘

$sortByCount is a convenient aggregation stage in MongoDB that groups documents by a specified expression and sorts the results in descending order of count. It’s essentially a shortcut for a common aggregation pattern:

// Equivalent of this:
[{ $group: { _id: "$field", count: { $sum: 1 } } }, { $sort: { count: -1 } }];

So instead of writing two stages ($group and $sort), MongoDB lets you do it in a single line:

{
  $sortByCount: "$field";
}

Real-World Scenario: E-Commerce Product Reviews 🌍

Imagine you're building an admin dashboard for an e-commerce app. You want to show which product category is being reviewed the most.

Your reviews collection looks like this:

{
  "_id": ObjectId("..."),
  "userId": "u123",
  "productId": "p789",
  "category": "electronics",
  "rating": 4,
  "review": "Great product!"
}

Now, to find out the most reviewed product categories, you can run:

db.reviews.aggregate([{ $sortByCount: "$category" }]);

Output 🧾:

[
  { "_id": "electronics", "count": 124 },
  { "_id": "books", "count": 89 },
  { "_id": "clothing", "count": 73 }
]

Just like that—you've got a frequency-sorted breakdown of product categories based on the number of reviews!


Why & Where to Use $sortByCount? 🧠

✅ When to Use:

  • When you need to quickly find most common values in a field.

  • To summarize large datasets without writing verbose pipelines.

  • For data exploration, to discover patterns or anomalies.

📍 Common Use Cases:

  • Top product categories, tags, or genres.

  • Most active users by action type.

  • Most common error codes in logs.

  • Most-used payment methods.

  • Most frequent search queries.


A Minor Pipeline Example 🔧

Let’s say you have a logs collection that stores user activities:

{
  "userId": "u42",
  "action": "login",
  "timestamp": ISODate("2025-04-14T10:20:00Z")
}

To get the most common actions:

db.logs.aggregate([{ $sortByCount: "$action" }]);

You’ll get a sorted list of actions performed, by frequency:

[
  { "_id": "login", "count": 356 },
  { "_id": "view_item", "count": 280 },
  { "_id": "add_to_cart", "count": 102 }
]

Simple, readable, and powerful.


Final Thoughts 🚀

MongoDB's $sortByCount is a time-saver and insight-giver when dealing with frequent value analysis. Instead of chaining multiple stages, this one-liner gives you frequency distribution that’s sorted and ready to use.

Whether you’re building dashboards, monitoring logs, or crunching product data, keep $sortByCount in your toolbox—because sometimes, knowing what shows up the most tells you everything you need to know.


👉 Tip: Want to apply filters before using $sortByCount? Just use a $match stage before it!

db.logs.aggregate([
  { $match: { action: { $ne: "logout" } } },
  { $sortByCount: "$action" },
]);

💬 What use case are you thinking of applying $sortByCount to?

Let me know in the comments or share your own cool aggregation tricks!


Thank You!

Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.

Happy Coding!
Darshit Anjaria

MongoDB: Essential Aggregation Stages

Part 8 of 9

A practical deep dive into MongoDB's aggregation framework - exploring essential pipeline stages, real world use cases, and performance tips to help you query smarter and build better.

Up next

A Guide to MongoDB $replaceRoot: Effortlessly Reshape Your Documents

Understand the process of flattening nested structures and modifying documents with $replaceRoot in MongoDB.