2
I have some data structured as follows:
"_id" : "",
"filmes" : [
{
"nome" : "Filme 1",
"categoria" : "terror",
"qtd" : 7
},
{
"nome" : "Filme 2",
"categoria" : "comedia",
"qtd" : 7
},
{
"nome" : "FIlme 3",
"categoria" : "terror",
"qtd" : 7
},
{
"nome" : "Filme 4",
"categoria" : "terror",
"qtd" : 7
},
{
"nome" : "Filme 5",
"categoria" : "comedia",
"qtd" : 7
},
{
"nome" : "Filme 6",
"categoria" : "romance",
"qtd" : 7
},
]
I am trying to develop a query that adds the values by category and brings me the data as follows (sum of "Qtd" by category):
"_id" : "",
"livros" : [
{
"categoria" : "terror",
"qtd" : 21
},
{
"categoria" : "comedia",
"qtd" : 14
},
{
"categoria" : "romance",
"qtd" : 7
},
]
I tried some stuff like:
db.filmes.aggregate(
[
{
$project:
{
_id: "$_id",
totalfilmes: { $sum: "$filmes.qtd" }
}
}
]
)
but I can’t aggregate by category. Anyone has any idea ?