- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- MongoDB query to add multiple documents
- MongoDB query to match documents with array values greater than a specific value
- MongoDB query to fetch a specific document rom documents with field value set using NumberInt()?
- Find MongoDB documents that contains specific field?
- Find documents that contains specific field in MongoDB?
- MongoDB query to get specific list of names from documents where the value of a field is an array
- MongoDB query to collectively match intersection of documents against a field
- MongoDB aggregation to fetch documents with specific field value?
- MongoDB query to implement nor query to fetch documents except a specific document
- MongoDB query to limit the returning values of a field?
- MongoDB query to display alternative documents with mapReduce() function and emit even field values
- Get count of array elements from a specific field in MongoDB documents?
- MongoDB query to update all documents matching specific IDs
- MongoDB query to display documents with a specific name irrespective of case
- Fetch specific field values in MongoDB

Advertisements