2

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.