简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM