Extract all the values and display in a single line with MongoDB

To extract all values from nested arrays and display them in a single line in MongoDB, use the $unwind operator to flatten arrays and $group with $push to combine all values into one array.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $unwind: "$arrayField.nestedArray" },
    { $group: { _id: null, result: { $push: "$arrayField.nestedArray" } } }
]);

Sample Data

db.demo389.insertOne({
    "details": [
        { "Name": ["Chris", "David"] },
        { "Name": ["Bob", "Mike"] },
        { "Name": ["Carol", "Sam"] },
        { "Name": ["David", "John"] }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e5d1d8f22064be7ab44e7f9")
}

View Sample Data

db.demo389.find();
{
    "_id": ObjectId("5e5d1d8f22064be7ab44e7f9"), 
    "details": [
        { "Name": ["Chris", "David"] }, 
        { "Name": ["Bob", "Mike"] },
        { "Name": ["Carol", "Sam"] }, 
        { "Name": ["David", "John"] }
    ] 
}

Extract All Values

db.demo389.aggregate([
    { $unwind: "$details" },
    { $unwind: "$details.Name" },
    { $project: {
        "_id": "$_id",
        "Name": "$details.Name"
    }},
    { $group: {
        _id: "_id",
        out: { $push: "$Name" }
    }},
    { $project: {
        "_id": 0,
        "NameArray": "$out"
    }}
]);
{ "NameArray": ["Chris", "David", "Bob", "Mike", "Carol", "Sam", "David", "John"] }

How It Works

  • First $unwind: Flattens the details array into separate documents
  • Second $unwind: Flattens each Name array to individual string values
  • $group: Combines all individual names back into a single array using $push
  • $project: Formats the final output with a clean field name

Conclusion

Use double $unwind operations followed by $group with $push to extract all values from nested arrays and combine them into a single array. This aggregation pipeline effectively flattens complex nested structures.

Updated on: 2026-03-15T02:46:45+05:30

749 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements