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
Find sum of fields inside array in MongoDB?
To find sum of fields inside array, use $sum. Let us create a collection with documents −
> db.demo96.insertOne(
... {
...
... "Name" : "Chris",
... "Details" : [
... {
... Marks:67
... },
... {
... Marks:33
... },
... {
... Marks:50
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2d6aadb8903cdd865577ad")
}
Display all documents from a collection with the help of find() method −
> db.demo96.find();
This will produce the following output −
{
"_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "Details" : [
{ "Marks" : 67 }, { "Marks" : 33 }, { "Marks" : 50 }
]
}
Following is the query to find sum of fields inside array in MongoDB −
> db.demo96.aggregate([
... { "$project": {
... "Name": 1,
... "TotalMarks": {
... "$sum": "$Details.Marks"
... }
... }}
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e2d6aadb8903cdd865577ad"), "Name" : "Chris", "TotalMarks" : 150 }Advertisements