- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 aggregate nested array
To aggregate nested array in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo441.insertOne( ... { ... ... "Name" : "David", ... "Age" : 21, ... ... "details" : [ ... { ... "id" : 1, ... "CountryName" : "US", ... "details1" : [ ... { ... "SubjectName" : "MySQL", ... "Score":56 ... }, ... { ... "SubjectName" : "MongoDB", ... "Score":78 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e78cc05bbc41e36cc3caeb7") }
Display all documents from a collection with the help of find() method −
> db.demo441.find();
This will produce the following output −
{ "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"), "Name" : "David", "Age" : 21, "details" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MySQL", "Score" : 56 }, { "SubjectName" : "MongoDB", "Score" : 78 } ] } ] }
Following is the query to aggregate nested array −
> db.demo441.aggregate([{ ... $addFields: { ... ResultOfDetails: { ... $map: { ... input: "$details", ... as: "output", ... in: { ... id: "$$output.id", ... CountryName: "$$output.CountryName", ... details1: { ... $let: { ... vars: { ... last: { ... $arrayElemAt: ["$$output.details1", -1] ... } ... }, ... in: { ... $cond: [{ ... $eq: ["$$last.Score", 78] ... }, ... ["$$last"], ... [] ... ... } ... } ... } ... } ... } ... } ... } ... }]).pretty();
This will produce the following output −
{ "_id" : ObjectId("5e78cc05bbc41e36cc3caeb7"), "Name" : "David", "Age" : 21, "details" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MySQL", "Score" : 56 }, { "SubjectName" : "MongoDB", "Score" : 78 } ] } ], "ResultOfDetails" : [ { "id" : 1, "CountryName" : "US", "details1" : [ { "SubjectName" : "MongoDB", "Score" : 78 } ] } ] }
Advertisements