Get the aggregated result and find the count of repeated values in different MongoDBndocuments

To count repeated values in different MongoDB documents, use the aggregate() method with the $group stage to group documents by a field and calculate the count using $sum.

Syntax

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

Sample Data

db.demo452.insertMany([
    { "StudentName": "John", "StudentAge": 21 },
    { "StudentName": "John", "StudentAge": 22 },
    { "StudentName": "John", "StudentAge": 23 },
    { "StudentName": "David", "StudentAge": 24 },
    { "StudentName": "David", "StudentAge": 25 }
]);

Display all documents from the collection ?

db.demo452.find();
{ "_id" : ObjectId("5e7b7e3371f552a0ebb0a6f3"), "StudentName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5e7b7e3671f552a0ebb0a6f4"), "StudentName" : "John", "StudentAge" : 22 }
{ "_id" : ObjectId("5e7b7e3971f552a0ebb0a6f5"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5e7b7e4371f552a0ebb0a6f6"), "StudentName" : "David", "StudentAge" : 24 }
{ "_id" : ObjectId("5e7b7e4571f552a0ebb0a6f7"), "StudentName" : "David", "StudentAge" : 25 }

Method 1: Simple Count of Repeated Values

db.demo452.aggregate([
    { $group: { _id: "$StudentName", count: { $sum: 1 } } },
    { $sort: { count: -1 } }
]);
{ "_id" : "John", "count" : 3 }
{ "_id" : "David", "count" : 2 }

Method 2: Complex Aggregation with Projection

db.demo452.aggregate([
    { $group: { _id: "$StudentName", count: { $sum: 1 } } },
    { $sort: { count: -1 } },
    { $group: { _id: 1, StudentName: { $push: { StudentName: "$_id", count: "$count" } } } },
    { $project: {
        first: { $arrayElemAt: ["$StudentName", 0] },
        second: { $arrayElemAt: ["$StudentName", 1] },
        others: { $slice: ["$StudentName", 2, { $size: "$StudentName" }] }
    } },
    { $project: {
        status: [
            "$first",
            "$second",
            {
                StudentName: "New Student Name",
                count: { $sum: "$others.count" }
            }
        ]
    } },
    { $unwind: "$status" },
    { $project: { _id: 0, StudentName: "$status.StudentName", count: "$status.count" } }
]);
{ "StudentName" : "John", "count" : 3 }
{ "StudentName" : "David", "count" : 2 }
{ "StudentName" : "New Student Name", "count" : 0 }

Key Points

  • $group groups documents by the specified field and counts occurrences
  • $sum: 1 counts each document in the group
  • $sort orders results by count in descending order

Conclusion

Use MongoDB's aggregate() with $group to count repeated values efficiently. The $sum: 1 accumulator counts document occurrences for each grouped field value.

Updated on: 2026-03-15T03:01:38+05:30

217 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements