MongoDB aggregation / math operation to sum score of a specific student

To sum scores of a specific student in MongoDB, use the aggregate() method with $match to filter by student name and $sum to calculate the total score.

Syntax

db.collection.aggregate([
    { "$match": { "Name": "StudentName" } },
    { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } }
]);

Sample Data

db.demo434.insertMany([
    {"Name": "Chris", "Score": 45},
    {"Name": "David", "Score": 55},
    {"Name": "Chris", "Score": 55}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e771603bbc41e36cc3cae93"),
        ObjectId("5e77161abbc41e36cc3cae94"),
        ObjectId("5e771624bbc41e36cc3cae95")
    ]
}

Display all documents from a collection with the help of find() method ?

db.demo434.find();
{ "_id": ObjectId("5e771603bbc41e36cc3cae93"), "Name": "Chris", "Score": 45 }
{ "_id": ObjectId("5e77161abbc41e36cc3cae94"), "Name": "David", "Score": 55 }
{ "_id": ObjectId("5e771624bbc41e36cc3cae95"), "Name": "Chris", "Score": 55 }

Example: Sum Chris's Total Score

Following is the query to sum score of a specific student ?

db.demo434.aggregate([
    { "$match": { "Name": "Chris"} },
    { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } }
]);
{ "_id": null, "TotalScore": 100 }

How It Works

  • $match: Filters documents to include only records where Name equals "Chris"
  • $group: Groups all matched documents together (_id: null) and calculates the sum using $sum: "$Score"

Conclusion

Use MongoDB's aggregation pipeline with $match and $sum operators to efficiently calculate total scores for specific students. The pipeline first filters by student name, then sums all matching score values.

Updated on: 2026-03-15T02:58:29+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements