Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 }Advertisements