Using count equivalent in MongoDB to find top users with max occurrence

To find the top users with maximum occurrence in MongoDB, use the $group stage with aggregate() to count occurrences, then $sort and $limit to get the top results.

Syntax

db.collection.aggregate([
    { $group: { _id: "$fieldName", count: { $sum: 1 } } },
    { $sort: { count: -1 } },
    { $limit: numberOfTopResults }
]);

Sample Data

Let us create a collection with user documents ?

db.demo264.insertMany([
    { "Name": "Chris" },
    { "Name": "David" },
    { "Name": "Chris" },
    { "Name": "Bob" },
    { "Name": "Chris" },
    { "Name": "Bob" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e47ed441627c0c63e7dba9e"),
        ObjectId("5e47ed471627c0c63e7dba9f"),
        ObjectId("5e47ed491627c0c63e7dbaa0"),
        ObjectId("5e47ed4c1627c0c63e7dbaa1"),
        ObjectId("5e47ed4e1627c0c63e7dbaa2"),
        ObjectId("5e47ed531627c0c63e7dbaa3")
    ]
}

Display all documents from the collection ?

db.demo264.find();
{ "_id": ObjectId("5e47ed441627c0c63e7dba9e"), "Name": "Chris" }
{ "_id": ObjectId("5e47ed471627c0c63e7dba9f"), "Name": "David" }
{ "_id": ObjectId("5e47ed491627c0c63e7dbaa0"), "Name": "Chris" }
{ "_id": ObjectId("5e47ed4c1627c0c63e7dbaa1"), "Name": "Bob" }
{ "_id": ObjectId("5e47ed4e1627c0c63e7dbaa2"), "Name": "Chris" }
{ "_id": ObjectId("5e47ed531627c0c63e7dbaa3"), "Name": "Bob" }

Example: Find Top 5 Users

The following query finds the top users with maximum occurrence ?

db.demo264.aggregate([
    { $group: { _id: "$Name", count: { $sum: 1 } } },
    { $sort: { count: -1 } },
    { $limit: 5 }
]);
{ "_id": "Chris", "count": 3 }
{ "_id": "Bob", "count": 2 }
{ "_id": "David", "count": 1 }

How It Works

  • $group groups documents by the Name field and counts occurrences using $sum: 1
  • $sort sorts by count in descending order (-1) to get highest counts first
  • $limit restricts the output to top 5 results

Conclusion

Use MongoDB's aggregation pipeline with $group, $sort, and $limit to efficiently find top users by occurrence count. This approach provides flexible counting and ranking capabilities for large datasets.

Updated on: 2026-03-15T02:09:54+05:30

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements