Each document in my collection has a property that is an array and that array has objects with properties such as total, index, etc. I want to group the documents by the sum of the total property of the second array element, like the query below. How can I make it happen?
I want to make this query work :
db.nwt_envio_contacto.aggregate({
$project:{
"visualizacoes":true,
"envio_id":true
}
},
{
$match:{
"envio_id":ObjectId("54c5ed8101ec09c26c7b23c6"),
"visualizacoes":{
$elemMatch:{
"index":1
}
}
}
},
{
$group:{
_id:null,
total:{
$sum:"visualizacoes.$.total"
}
}
})
Assume that I have a collection with this document :
{
"_id":ObjectId("54c5ed8101ec09c26c7b23c8"),
"envio_id":ObjectId("54c5ed8101ec09c26c7b23c6"),
"visualizacoes":[
{
"primeira":"2015-01-26 09:34:58",
"ultima":"2015-01-26 14:17:18",
"index":2,
"total":4
},
{
"primeira":"2015-01-26 09:35:13",
"ultima":"2015-01-26 09:35:43",
"index":2,
"total":3
}
]
}
Basically I want to sum the total attribute of all visualizacoes objects that have the index equal to 1.