Working with MongoDB concatArrays in project on existing multi-array field

The $concatArrays operator is used to concatenate arrays and return the concatenated array. When working with multi-dimensional arrays, you can combine it with $reduce to flatten and concatenate nested arrays.

Syntax

{
  "$project": {
    "newFieldName": {
      "$reduce": {
        "input": "$arrayField",
        "initialValue": [],
        "in": { "$concatArrays": ["$$this", "$$value"] }
      }
    }
  }
}

Sample Data

Let us create a collection with documents ?

db.demo338.insertOne({
  "Name": "Chris",
  "Marks1": [ [56,67,45], [67,89,90,91] ]
});
{
  "acknowledged" : true,
  "insertedId" : ObjectId("5e5299baf8647eb59e56209f")
}

Display all documents from a collection with the help of find() method ?

db.demo338.find().pretty();
{
  "_id" : ObjectId("5e5299baf8647eb59e56209f"),
  "Name" : "Chris",
  "Marks1" : [
    [
      56,
      67,
      45
    ],
    [
      67,
      89,
      90,
      91
    ]
  ]
}

Example: Concatenating Multi-Array Field

Following is the query to work on the existing multi-array field and concatenate arrays ?

db.demo338.aggregate([
  { "$project": {
    "Marks": {
      "$reduce": {
        "input": "$Marks1",
        "initialValue": [],
        "in": { "$concatArrays": ["$$value", "$$this"] }
      }
    }
  }}
]);
{ "_id" : ObjectId("5e5299baf8647eb59e56209f"), "Marks" : [ 56, 67, 45, 67, 89, 90, 91 ] }

How It Works

  • $reduce iterates through each sub-array in Marks1
  • $$value accumulates the concatenated result (starts as empty array)
  • $$this represents the current sub-array being processed
  • $concatArrays merges the accumulator with the current sub-array

Conclusion

Use $concatArrays with $reduce to flatten multi-dimensional arrays in MongoDB. The $reduce operator iterates through nested arrays while $concatArrays concatenates them into a single flat array.

Updated on: 2026-03-15T02:32:42+05:30

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements