Can anyone help me to group the data by key without using $unwind nor $group stage ? The reason why I don't want to use $unwind nor $group stage is because I want to be able to use the pipeline in a updateMany(filter, pipeline) operation so the stages I can use are limited to: $addFields (= $set), $project (= $unset) and $replaceRoot (= $replaceWith).
The input data looks like this:
[
{
key: "alpha",
value: {
name: "foo",
},
},
{
key: "beta",
value: {
name: "bar",
},
},
{
key: "alpha",
value: {
name: "baz",
},
},
]
The result I would like to get:
[
{
key: "alpha",
values: [
{
name: "foo",
},
{
name: "baz",
},
],
},
{
key: "beta",
values: [
{
name: "bar",
},
],
},
]
I believe that it's doable by using $reduce but I'm newbie with mongodb aggregation so I'm struggling to accumulate objects in array conditionally.
Thanks