Medo
Medo

Reputation: 83

Concat all the arrays from different objects in mongoDB

i 'am starting discovering mongodb , i'd like to concat the images to be in the same array

The example:

{user_id:01, images:[10,20,30,40,50]}
{user_id:02, images:[11,22,33,44,55]}
{user_id:03, images:[12,22,32,42,52]}
{user_id:04, images:[13,23,33,43,53]}

The result wanted:

 images:[10,20,30,40,50,11,22,33,44,55,12,22,32,42,52,13,23,33,43,53]

i found through the Doc the $aggreagation solution , here is what i have tried:

  db.results.aggregate([{ $project: { images: { $concatArrays: ["$images"]}}}])

but it just concat the array from the same object , in my case as i mentioned in result wantedto concat all the array having the name images from different objects as one

Upvotes: 3

Views: 4244

Answers (2)

dnickless
dnickless

Reputation: 10918

You can run the following aggregation query to get your result:

db.collection.aggregate([
{
    $unwind: "$images" // flatten the "images" array into separate documents
},
{
    $group: { // group all documents
        "_id": null, // into the same bucket
        "images": { $push: "$images"} // and push every image entry into an array called "images"
    }
},
{
    $project: {
        _id: 0 // to get rid of the "_id" field if needed
    }
}])

Upvotes: 3

mickl
mickl

Reputation: 49945

You need two steps:

$group with const value (like null) as a grouping _id to get an array of arrays (from all documents) and $reduce to flatten all arrays

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

Upvotes: 5

Related Questions