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
Aggregate based on array value to sum values in different MongoDB documents?
For this, use aggregate() in MongoDB. Let us first create a collection with documents −
> db.demo126.insertOne(
... {
... "StudentDetails" : {
... "Number" : 1,
... "OtherDetails" : [
... {
... "Name" : "Chris",
... "Score" : 55
...
... }
... ].. }}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e304b3068e7f832db1a7f56")
}
>
>
> db.demo126.insertOne(
... {
... "StudentDetails" : {
...
... "Number" : 2,
... "OtherDetails" : [
... {
... "Name" : "Chris",
... "Score" : 35
...
... },
... {
... "Name" : "David",
... "Score" : 87
... }
...
... ]
... }}
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e304b3068e7f832db1a7f57")
}
Display all documents from a collection with the help of find() method −
> db.demo126.find();
This will produce the following output −
{ "_id" : ObjectId("5e304b3068e7f832db1a7f56"), "StudentDetails" : { "Number" : 1, "OtherDetails" : [ { "Name" : "Chris", "Score" : 55 } ] } }
{ "_id" : ObjectId("5e304b3068e7f832db1a7f57"), "StudentDetails" : { "Number" : 2, "OtherDetails" : [ { "Name" : "Chris", "Score" : 35 }, { "Name" : "David", "Score" : 87 } ] } }
Following is the query to aggregate based on array value −
> db.demo126.aggregate([
... {
... $unwind:"$StudentDetails.OtherDetails"
... },
... {
... $group:{
... _id:"$StudentDetails.OtherDetails.Name",
... quantity:{
... $sum:"$StudentDetails.OtherDetails.Score"
... }
... }
... }
... ])
This will produce the following output −
{ "_id" : "David", "quantity" : 87 }
{ "_id" : "Chris", "quantity" : 90 }Advertisements