Concatenate all the arrays of the elements in a collection [MongoDB]

Viewed 566

Sorry, I didn't get the MongoDB aggregation well. How can I achieve with an aggregation this:

[
  {array: [1,2,3] },
  {array: [4,5,6] },
  {array: [7,8,9] }
]


desired result:
[1,2,3,4,5,6,7,8,9]

Does the performance change if instead of using MongoDB aggregation I consider documents as normal objects?

2 Answers

Aggregation is always a better option instead of using some language code and that is why database provides such type of relief to get the results in one go.

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "data": { "$push": "$array" }
  }},
  { "$project": {
    "_id": 0,
    "data": {
      "$reduce": {
        "input": "$data",
        "initialValue": [],
        "in": { "$concatArrays": ["$$this", "$$value"] }
      }
    }
  }}
])

The only thing you have to take care here is the size of the returned result for single document should not exceed more 16MB Bson limit. More you can learn from here

You can $group by null to get an array of arrays as a single document and then you can run $reduce with $concatArrays to flatten that array:

db.col.aggregate([
    {
        $group: {
            _id: null,
            array: { $push: "$array" }
        }
    },
    {
        $project: {
            _id: 0,
            array: {
                $reduce: {
                    input: "$array",
                    initialValue: [],
                    in: { $concatArrays: [ "$$value", "$$this" ] }
                }
            }
        }
    }
])

MongoDB Playground

Related