4

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?

Ashh
  • 44,693
  • 14
  • 105
  • 132
Niccolò Caselli
  • 783
  • 2
  • 10
  • 28

2 Answers2

2

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

Ashh
  • 44,693
  • 14
  • 105
  • 132
  • Thank you very much you and @mickl. In my project, I divided the array into several documents just to avoid the 16MB limit. For this reason, I believe that the array would go beyond the limit. So for my case, it is better to use some language code? – Niccolò Caselli Jun 04 '19 at 19:51
  • 1
    Yes it would but in my opinion 16 mb is not a small unit. – Ashh Jun 04 '19 at 20:18
1

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

mickl
  • 48,568
  • 9
  • 60
  • 89