Challenge - $addFields - Dynamic keys

Is it possible to add a field with an aggregated value as the key of the new field?

const pipeline = [
    {'$group': {_id: '$months', value: { $avg: '$data' }}},
    {'$addFields': { ' $_id' : '$value'}}]

// Target Example Output
{april : 5.0}

@max_matinpalo, welcome to the MongoDB Community forum!

You can try this using the $arrayToObject operator.

Hey Prasad, thanks a lot for your quick response.

$arrayToObject looks veryuseful but doesn’t solve this case. In attachment image of this challenge.

Hello @max_matinpalo, that is the way to solve the question you have - use the $arrayToObject (and, I have a gentle suggestion that first you try examples from the documentation and then apply to your challenge :slight_smile: ).

1 Like

$arrayToObject expects its input as an array of key value pairs, like this:

[ {k: "key", v: "value" } ]

So you need to transform the output of {'$group': {_id: '$months', value: { $avg: '$data' }}}.

Try something like this:

{$addFields:{new:{$arrayToObject: [ {k: "$_id", v: "$value"} ]}}}

Now this will have the new object as a subdocument, so if you wanted it to be top level you would have to use $replaceWith probably with $mergeObjects if there are other fields you need to preserve.



Asya thank you very much. Now 100% clear. :slightly_smiling_face:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.