

- 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 query to sum specific fields
To sum specific fields, use aggregate along with $sum. Let us first create a collection with documents −
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":50,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cec29e4dae213890ac55") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":102,"Price":200,"Status":"Inactive"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06ced19e4dae213890ac56") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":3000,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cedd9e4dae213890ac57") } > db.getSumOfFieldsDemo.insertOne({"Customer_Id":103,"Price":400,"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06cee79e4dae213890ac58") }
Following is the query to display all documents from a collection with the help of find() method −
> db.getSumOfFieldsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e06cec29e4dae213890ac55"), "Customer_Id" : 101, "Price" : 50, "Status" : "Active" } { "_id" : ObjectId("5e06ced19e4dae213890ac56"), "Customer_Id" : 102, "Price" : 200, "Status" : "Inactive" } { "_id" : ObjectId("5e06cedd9e4dae213890ac57"), "Customer_Id" : 101, "Price" : 3000, "Status" : "Active" } { "_id" : ObjectId("5e06cee79e4dae213890ac58"), "Customer_Id" : 103, "Price" : 400, "Status" : "Active" }
Following is the query to sum specific fields based on ACTIVE status −
> db.getSumOfFieldsDemo.aggregate([ { $match: { Status: "Active" } }, { $group: { _id: "$Customer_Id", TotalSum: { $sum: "$Price" } } } ]);
This will produce the following output −
{ "_id" : 103, "TotalSum" : 400 } { "_id" : 101, "TotalSum" : 3050 }
- Related Questions & Answers
- MongoDB query to return specific fields from an array?
- MongoDB query to get only specific fields in nested array documents?
- MongoDB query to update selected fields
- MongoDB query to sum specific key values with terminal commands?
- Update only specific fields in MongoDB?
- MongoDB query condition to compare two fields?
- MongoDB query to update only certain fields?
- MongoDB order by two fields sum?
- MongoDB query to return only specific fields (phone numbers) in the form of an array?
- MongoDB query condition on comparing 2 fields?
- MongoDB query for fields in embedded document?
- MongoDB query to remove a specific document
- MongoDB query to exclude both the fields with FALSE
- MongoDB collection query to exclude some fields in find()?
- MongoDB query to group several fields using aggregation framework?
Advertisements