I have some data structured like this:
"_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'm trying to develop a query that adds up 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 things like:
db.filmes.aggregate(
[
{
$project:
{
_id: "$_id",
totalfilmes: { $sum: "$filmes.qtd" }
}
}
]
)
but I can not add by category. Anyone have any ideas?