I'm trying to do an array based on the next structure:
{
_id:573a1390f
plot:"A greedy tycoon decides, on a whim, to corner the world market in whea…",
genres:"Short","Drama",
countries:"México","USA"
},
{
_id:573a1390f
plot:"A woman, with the aid of her police officer sweetheart, endeavors to u…",
genres:"Drama",
countries:"México","USA","Canada"
}
What Im trying to do is to provide an output like this:
Country|Genre|Total Rows
México |Short|1
México |Drama|2
USA |Short|1 and so.
I have come up with the following:
{
$unwind:
{
path: "$Genres"
}
}
{
$unwind:
{
path: "$Countries"
}
}
{
$Addfields:{CuentaxGenero:{sum:1}}
}
{
$group:
{
_id: {pais:"$countries",genero:"$genres"},
Total:{$sum:1}
}
}
But the output at the end the field _id
still looks like an object and can´t place it like a field. Is there any way to unwind
the aggregation?
I'm just learning, hope you can help me.
You need the
$project
stage to decorate the output document, by flattening the_id
object to multiple fields forcountry
, andgenre
.The
$addFields
stage can be removed as the added field doesn't seem to be needed to further stages.Demo @ Mongo Playground