
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
Aggregation in MongoDB for Nested Documents
For aggregation in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo199.insertOne( ... { ... "details1":{ ... "details2":{ ... "details3":{ ... "Name":"Chris", ... "details4":{ ... "details5":{ ... "v1":10, ... "v2":20, ... "v3":30 ... } ... } ... }}}} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3c24aa03d395bdc21346e2") } > > db.demo199.insertOne( ... { ... "details1":{ ... "details2":{ ... "details3":{ ... "Name":"Chris", ... "details4":{ ... "details5":{ ... "v1":30, ... "v2":40, ... "v3":50 ... } ... } ... }}}} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3c24ab03d395bdc21346e3") }
Display all documents from a collection with the help of find() method −
> db.demo199.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c24aa03d395bdc21346e2"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 10, "v2" : 20, "v3" : 30 } } } } } } { "_id" : ObjectId("5e3c24ab03d395bdc21346e3"), "details1" : { "details2" : { "details3" : { "Name" : "Chris", "details4" : { "details5" : { "v1" : 30, "v2" : 40, "v3" : 50 } } } } } }
Following is the query for aggregation in MongoDB for nested documents −
> var out = [ ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$group": { ... "_id": "$details1.details2._id", ... "v1": { "$sum": "$details1.details2.details3.details4.details5.v1" }, ... "v2": { "$sum": "$details1.details2.details3.details4.details5.v2" }, ... "v3": { "$sum": "$details1.details2.details3.details4.details5.v3" }, ... } ... } ...] > result = db.demo199.aggregate(out);
This will produce the following output −
{ "_id" : null, "v1" : 40, "v2" : 60, "v3" : 80 }
Advertisements