- 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
How to sum the value of a key across all documents in a MongoDB collection?
To get sum the value of a key across all documents in a MongoDB collection, you can use aggregate().
To understand the above concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.sumOfValueDemo.insertOne({"Name":"Larry","Amount":14.50}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ee7272f684a30fbdfd592") } > db.sumOfValueDemo.insertOne({"Name":"Mike","Amount":15.68}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ee7342f684a30fbdfd593") } > db.sumOfValueDemo.insertOne({"Name":"Carol","Amount":50.32}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ee7412f684a30fbdfd594") } > db.sumOfValueDemo.insertOne({"Name":"David","Amount":120.90}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ee7532f684a30fbdfd595") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.sumOfValueDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8ee7272f684a30fbdfd592"), "Name" : "Larry", "Amount" : 14.5 } { "_id" : ObjectId("5c8ee7342f684a30fbdfd593"), "Name" : "Mike", "Amount" : 15.68 } { "_id" : ObjectId("5c8ee7412f684a30fbdfd594"), "Name" : "Carol", "Amount" : 50.32 } { "_id" : ObjectId("5c8ee7532f684a30fbdfd595"), "Name" : "David", "Amount" : 120.9 }
Here is the query to sum the value of a key across all documents in a MongoDB collection:
> db.sumOfValueDemo.aggregate({ ... $group: { ... _id: '', ... "Amount": { $sum: '$Amount' } ... } ... }, { ... $project: { ... _id: 0, ... "TotalAmount": '$Amount' ... } ... });
The following is the output:
{ "TotalAmount" : 201.4 }
Advertisements