Is there a MongoDB query to concatenate deep sub-lists?

To concatenate deep sub-lists in MongoDB, use the $unwind operator in an aggregation pipeline to flatten nested arrays, then apply additional transformations like sorting, limiting, and reshaping the results.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField1" },
    { $unwind: "$arrayField1.nestedArray" },
    { $sort: { "arrayField1.nestedArray.field": 1 } },
    { $replaceRoot: { newRoot: "$arrayField1.nestedArray" } }
]);

Sample Data

db.demo70.insertOne({
    "first": [
        {
            "details": {
                "second": [
                    {
                        "StudentDetails": {
                            "Score": 10
                        }
                    },
                    {
                        "StudentDetails": {
                            "Score": 20
                        }
                    },
                    {
                        "StudentDetails": {
                            "Score": 30
                        }
                    }
                ]
            }
        },
        {
            "details": {
                "second": [
                    {
                        "StudentDetails": {
                            "Score": 11
                        }
                    },
                    {
                        "StudentDetails": {
                            "Score": 18
                        }
                    },
                    {
                        "StudentDetails": {
                            "Score": 29
                        }
                    }
                ]
            }
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e29ad4d0912fae76b13d76d")
}

Example: Concatenate and Sort Deep Sub-Lists

To flatten the nested arrays and extract the top 3 highest scores ?

db.demo70.aggregate([
    { $unwind: "$first" },
    { $unwind: "$first.details.second" },
    { $sort: { "first.details.second.StudentDetails.Score": -1 } },
    { $limit: 3 },
    { $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
    { $sort: { "Score": 1 } }
]);
{ "Score": 20 }
{ "Score": 29 }
{ "Score": 30 }

How It Works

  • $unwind: "$first" − Flattens the outer array, creating separate documents for each array element
  • $unwind: "$first.details.second" − Flattens the nested "second" array
  • $sort − Sorts by Score in descending order
  • $limit: 3 − Limits results to top 3 documents
  • $replaceRoot − Replaces the document root with StudentDetails object

Conclusion

Use multiple $unwind stages to flatten deeply nested arrays in MongoDB. This allows you to concatenate, sort, and transform complex nested structures into flat result sets for easier processing.

Updated on: 2026-03-15T01:49:50+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements