MongoDB nested group?
You will need two groups in this case. The first group generates a stream of documents with one document per term and category:
{ $group : { _id : { category: "$category", term: "$term", }, total: { $sum : 1 } } }
A second group will then merge all documents with the same term into one, using the $push operator to merge the categories into an array:
{ $group : { _id : "$_id.category", terms: { $push: { term:"$_id.term", total:"$total" } } } }
Query:
db.getCollection('orders').aggregate([ {$match:{ tipo: {$regex:"[A-Z]+"} } }, {$group: { _id:{ codigo:"1", tipo:"$tipo", }, total:{$sum:1} } }, {$group: { _id:"$_id.codigo", tipos: { $push: { tipo:"$_id.tipo", total:"$total" } }, totalGeneral:{$sum:"$total"} } }]);
Response:
{"_id" : "1","tipos" : [ { "tipo" : "TIPO_01", "total" : 13.0 }, { "tipo" : "TIPO_02", "total" : 2479.0 }, { "tipo" : "TIPO_03", "total" : 12445.0 }, { "tipo" : "TIPO_04", "total" : 12445.0 }, { "tipo" : "TIPO_05", "total" : 21.0 }, { "tipo" : "TIPO_06", "total" : 21590.0 }, { "tipo" : "TIPO_07", "total" : 1065.0 }, { "tipo" : "TIPO_08", "total" : 562.0 }],"totalGeneral" : 50620.0
}