Using MongoDB Aggregate and GroupBy to get the frequency of name record

To get the frequency of name records in MongoDB, use the aggregation framework with $group stage to group documents by name and count occurrences using $sum.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$fieldName",
            Frequency: { $sum: 1 }
        }
    }
]);

Create Sample Data

db.demo232.insertMany([
    {_id: 101, Name: "Chris"},
    {_id: 102, Name: "Bob"},
    {_id: 103, Name: "Bob"},
    {_id: 104, Name: "David"},
    {_id: 105, Name: "Chris"}
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 101,
        "1": 102,
        "2": 103,
        "3": 104,
        "4": 105
    }
}

Display Sample Data

db.demo232.find();
{ "_id": 101, "Name": "Chris" }
{ "_id": 102, "Name": "Bob" }
{ "_id": 103, "Name": "Bob" }
{ "_id": 104, "Name": "David" }
{ "_id": 105, "Name": "Chris" }

Get Name Frequency Using Aggregation

db.demo232.aggregate([
    {
        $group: {
            _id: "$Name",
            Frequency: { $sum: 1 }
        }
    }
]);
{ "_id": "David", "Frequency": 1 }
{ "_id": "Bob", "Frequency": 2 }
{ "_id": "Chris", "Frequency": 2 }

How It Works

  • $group groups documents by the Name field value
  • _id: "$Name" sets the grouping key to the Name field
  • $sum: 1 counts each document in the group by adding 1

Conclusion

Use MongoDB's $group aggregation stage with $sum: 1 to count document frequencies by any field. This efficiently calculates how many times each unique value appears in your collection.

Updated on: 2026-03-15T02:00:55+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements