How to maintain the top count of array elements in MongoDB?

To maintain the top count of array elements in MongoDB, use the aggregation framework with $unwind to flatten arrays, $group to count frequencies, $sort to order by count, and $limit to get the top N elements.

Syntax

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

Sample Data

db.topCountArrayDemo.insertMany([
    { "StudentId": 101, "StudentSubject": ["C", "MongoDB"] },
    { "StudentId": 102, "StudentSubject": ["C", "Java"] },
    { "StudentId": 103, "StudentSubject": ["C", "MongoDB"] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display all documents to verify the data ?

db.topCountArrayDemo.find().pretty();
{
    "_id": ObjectId("5cc6b3209cb58ca2b005e669"),
    "StudentId": 101,
    "StudentSubject": [
        "C",
        "MongoDB"
    ]
}
{
    "_id": ObjectId("5cc6b3219cb58ca2b005e66a"),
    "StudentId": 102,
    "StudentSubject": [
        "C",
        "Java"
    ]
}
{
    "_id": ObjectId("5cc6b3229cb58ca2b005e66b"),
    "StudentId": 103,
    "StudentSubject": [
        "C",
        "MongoDB"
    ]
}

Get Top 2 Array Element Counts

db.topCountArrayDemo.aggregate([
    {
        $unwind: "$StudentSubject"
    },
    {
        $group: {
            _id: "$StudentSubject",
            Frequency: { $sum: 1 }
        }
    },
    {
        $sort: { Frequency: -1 }
    },
    {
        $limit: 2
    }
]);
{ "_id": "C", "Frequency": 3 }
{ "_id": "MongoDB", "Frequency": 2 }

How It Works

  • $unwind creates separate documents for each array element
  • $group groups by element value and counts occurrences using $sum: 1
  • $sort orders results by frequency in descending order (-1)
  • $limit restricts output to the top N most frequent elements

Conclusion

Use MongoDB's aggregation pipeline to efficiently count and rank array elements. The combination of $unwind, $group, $sort, and $limit provides a powerful way to analyze array data frequencies.

Updated on: 2026-03-15T00:53:56+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements