Bierbarbar
Bierbarbar

Reputation: 1479

update array of objects with an array in a mongodb aggregation

I have the following situation in my aggregation: At some point my documents are holding an array of objects and an array of the same length at the root level. An example would be:

{_id:0,
 cars:[{name:"vw polo",door:3},{name:"vw golf",door:5}],
 possible_colors:[["black","blue"],["white"]]}

What I'm trying now is to update project the possible colors into each object of the cars array. The expected result should look as follows.

{_id:0,
 cars:[{name:"vw polo",door:3,possible_colors:["black","blue"]},
       {name:"vw golf",door:5,possible_colors:["white"]}],
 }

I already tried {$addfields:{cars:{$zip:[$cars,$possible_colors]}}}, but this creates a list of arrays, where each array contains the object and the correct subarray, but i was not able to merge them.

Upvotes: 2

Views: 363

Answers (1)

mickl
mickl

Reputation: 49945

The $zip operator is a good approach however you need additional $map along with $mergeObjects in order to get the desired structure:

db.collection.aggregate([
    {
        $addFields: {
            cars: {
                $map: {
                    input: { $zip: { inputs: [ "$cars", "$possible_colors" ] } },
                    in: {
                        $mergeObjects: [
                            { $arrayElemAt: [ "$$this", 0 ] },
                            { possible_colors: { $arrayElemAt: [ "$$this", 1 ] } }
                        ]
                    }
                }
            }
        }
    }
])

Mongo Playground

Upvotes: 2

Related Questions