

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB aggregation / math operation to sum score of a specific student
To sum, use aggregate() along with $sum. Let us create a collection with documents −
> db.demo434.insertOne({"Name":"Chris","Score":45}); { "acknowledged" : true, "insertedId" : ObjectId("5e771603bbc41e36cc3cae93") } > db.demo434.insertOne({"Name":"David","Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e77161abbc41e36cc3cae94") } > db.demo434.insertOne({"Name":"Chris","Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5e771624bbc41e36cc3cae95") }
Display all documents from a collection with the help of find() method −
> db.demo434.find();
This will produce the following output −
{ "_id" : ObjectId("5e771603bbc41e36cc3cae93"), "Name" : "Chris", "Score" : 45 } { "_id" : ObjectId("5e77161abbc41e36cc3cae94"), "Name" : "David", "Score" : 55 } { "_id" : ObjectId("5e771624bbc41e36cc3cae95"), "Name" : "Chris", "Score" : 55 }
Following is the query tom sum score of a specific student −
> db.demo434.aggregate([ ... { "$match": { "Name": "Chris"} }, ... { "$group": { "_id": null, "TotalScore": { "$sum": "$Score" } } } ... ]);
This will produce the following output −
{ "_id" : null, "TotalScore" : 100 }
- Related Questions & Answers
- How to calculate a sum of specific documents using MongoDB aggregation?
- Replace value with a string literal during MongoDB aggregation operation
- MongoDB query (aggregation framework) to match a specific field value
- C++ code to find rank of student from score table
- MongoDB aggregation to fetch documents with specific field value?
- Sum the score of duplicate column values in MongoDB documents?
- MongoDB aggregation to sum product price with similar IDs
- MongoDB query to sum specific fields
- How to get the 2nd highest value from a table with Student Score?
- Can we do math operation on Python Strings?
- C++ code to find maximum score we can assign to first student
- MongoDB divide aggregation operator?
- MongoDB aggregation and projection?
- Is it possible to sum two fields in MongoDB using the Aggregation framework?
- MongoDB aggregation framework to sort by length of array?
Advertisements