- 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 query to add up the values of a specific field in documents
Let us create a collection with documents −
> db.demo677.insertOne({Value:10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421f404263e90dac943f8") } > db.demo677.insertOne({Value:50}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421f704263e90dac943f9") } > db.demo677.insertOne({Value:20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421fa04263e90dac943fa") } > db.demo677.insertOne({Value:20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea421fe04263e90dac943fb") }
Display all documents from a collection with the help of find() method −
> db.demo677.find();
This will produce the following output −
{ "_id" : ObjectId("5ea421f404263e90dac943f8"), "Value" : 10 } { "_id" : ObjectId("5ea421f704263e90dac943f9"), "Value" : 50 } { "_id" : ObjectId("5ea421fa04263e90dac943fa"), "Value" : 20 } { "_id" : ObjectId("5ea421fe04263e90dac943fb"), "Value" : 20 }
Following is the query to add up the values of a specific field −
> db.demo677.aggregate({ $group: { _id : null, sum : { $sum: "$Value" } } });
This will produce the following output −
{ "_id" : null, "sum" : 100 }
Advertisements