- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 }
Advertisements