Trying to condense an array with key value pairs into an array of objects with the key and all the unique values for that key.
I have a structure like:
{
fruits: [
{fruit: apple, type: gaja},
{fruit: apple, type: honey-crisp},
{fruit: apple, type: fuji},
{fruit: cherry, type: black},
{fruit: cherry, type: red},
{fruit: cherry, type: red},
]
}
How can I convert it to:
{
fruits: [
{fruit: apple, types: [gaja, honey-crisp, fuji]},
{fruit: cherry, types: [black, red]}
]
}
Using mongo aggregations I managed to get the first structure from my data using $group and $addToSet. Not sure how to map the array to new object with a key and list of values
3
Answers
Maybe something like this:
Explained:
Playground
Here’s another way to do it by using
"$reduce"
. Comments are in the aggregation pipeline.Try it on mongoplayground.net.
Here’s another, another way using a multiple
"$map"
and"$setUnion"
to get unique array members.Try it on mongoplayground.net.