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 } ] } ] }