How to get array from a MongoDB collection?

To get an array from a MongoDB collection, you can use the aggregation framework with $unwind and $group operators to extract and collect array elements from nested documents.

Syntax

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

Sample Data

db.getArrayDemo.insertOne({
    "CustomerId": 101,
    "CustomerDetails": [
        {
            "CustomerName": "Larry",
            "CustomerFriendDetails": [
                { "CustomerFriendName": "Sam" },
                { "CustomerFriendName": "Robert" }
            ]
        },
        {
            "CustomerName": "Chris",
            "CustomerFriendDetails": [
                { "CustomerFriendName": "David" },
                { "CustomerFriendName": "Carol" }
            ]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cda4949b50a6c6dd317adb7")
}

Display Collection Documents

db.getArrayDemo.find().pretty();
{
    "_id": ObjectId("5cda4949b50a6c6dd317adb7"),
    "CustomerId": 101,
    "CustomerDetails": [
        {
            "CustomerName": "Larry",
            "CustomerFriendDetails": [
                { "CustomerFriendName": "Sam" },
                { "CustomerFriendName": "Robert" }
            ]
        },
        {
            "CustomerName": "Chris",
            "CustomerFriendDetails": [
                { "CustomerFriendName": "David" },
                { "CustomerFriendName": "Carol" }
            ]
        }
    ]
}

Extract Array from Nested Documents

db.getArrayDemo.aggregate([
    { "$unwind": "$CustomerDetails" },
    { "$unwind": "$CustomerDetails.CustomerFriendDetails" },
    {
        "$group": {
            "_id": null,
            "CustomerFriendDetails": { "$push": "$CustomerDetails.CustomerFriendDetails.CustomerFriendName" }
        }
    }
]);
{ "_id": null, "CustomerFriendDetails": [ "Sam", "Robert", "David", "Carol" ] }

How It Works

  • $unwind deconstructs the CustomerDetails array into separate documents
  • Second $unwind flattens the nested CustomerFriendDetails arrays
  • $group with $push collects all friend names into a single array

Conclusion

Use MongoDB's aggregation pipeline with $unwind to flatten nested arrays and $group with $push to extract and collect specific array elements from complex document structures into a single result array.

Updated on: 2026-03-15T01:23:27+05:30

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements