Aggregate multiple arrays into one huge array with MongoDB?

To aggregate multiple arrays into a single array in MongoDB, use the $concatArrays operator within the $project stage of an aggregation pipeline. This combines arrays from different fields into one unified array.

Syntax

db.collection.aggregate([
    {
        $project: {
            combinedArray: {
                $concatArrays: ["$array1", "$array2", "$array3"]
            }
        }
    }
])

Sample Data

db.demo119.insertOne({
    "_id": 101,
    "WebDetails": [
        {
            "ImagePath": "/all/image1",
            "isCorrect": "false"
        },
        {
            "ImagePath": "/all/image2",
            "isCorrect": "true"
        }
    ],
    "ClientDetails": [
        {
            "Name": "Chris",
            "isCorrect": "false"
        },
        {
            "Name": "David",
            "isCorrect": "true"
        }
    ]
});
{ "acknowledged": true, "insertedId": 101 }

Method 1: Simple Array Concatenation

Combine all arrays into a single array using $concatArrays ?

db.demo119.aggregate([
    {
        $project: {
            AllDetails: {
                $concatArrays: ["$WebDetails", "$ClientDetails"]
            }
        }
    }
])
{
    "_id": 101,
    "AllDetails": [
        { "ImagePath": "/all/image1", "isCorrect": "false" },
        { "ImagePath": "/all/image2", "isCorrect": "true" },
        { "Name": "Chris", "isCorrect": "false" },
        { "Name": "David", "isCorrect": "true" }
    ]
}

Method 2: Filter Combined Arrays

Combine arrays and filter for specific conditions using $setUnion and $filter ?

db.demo119.aggregate([
    {
        $project: {
            AllDetails: {
                $filter: {
                    input: {
                        $setUnion: [
                            { $ifNull: ["$WebDetails", []] },
                            { $ifNull: ["$ClientDetails", []] }
                        ]
                    },
                    as: "out",
                    cond: { $eq: ["$$out.isCorrect", "false"] }
                }
            }
        }
    },
    {
        $match: { "AllDetails.0": { $exists: true } }
    }
])
{
    "_id": 101,
    "AllDetails": [
        { "ImagePath": "/all/image1", "isCorrect": "false" },
        { "Name": "Chris", "isCorrect": "false" }
    ]
}

Key Differences

  • $concatArrays preserves array order and allows duplicates
  • $setUnion removes duplicates and creates a mathematical set
  • $ifNull handles cases where array fields might be missing or null

Conclusion

Use $concatArrays for simple array merging or $setUnion with $filter for combining arrays with deduplication and conditional filtering. Both approaches effectively aggregate multiple arrays into a single unified array.

Updated on: 2026-03-15T01:57:46+05:30

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements