Hello! Immediately quote an example of data (JSON is invalid, it is not important):
{ "_id":ObjectId("57989a4eb9b56b535b29751d"), "subid":"adwords", "extrasubid":[ { "subid":"ua", "_id":ObjectId("57989a566cb2296a5bc062fa"), "leadPrice":0, "revenue":0, "registrations":0, "hits":34 }, { "subid":"ru", "_id":ObjectId("5798abcc4d31957714ca7736"), "uniques":0, "leadPrice":0, "revenue":0, "registrations":2, "hits":10 } ], "__v":3 }{ "_id":ObjectId("5798a25e213c708b793ed04b"), "subid":"google", "extrasubid":[ { "subid":"google", "_id":ObjectId("5798a282213c708b793ed04d"), "leadPrice":0, "revenue":0, "registrations":0, "hits":9 } ], "__v":1 } So, in each collection I need to add the amount of revenue , registrations , hits from each extrasubid object to make something like this:
{ "_id":ObjectId("57989a4eb9b56b535b29751d"), "subid":"adwords", "extrasubid":[ { "subid":"ua", "_id":ObjectId("57989a566cb2296a5bc062fa"), "leadPrice":0, "revenue":0, "registrations":0, "hits":34 }, { "subid":"ru", "_id":ObjectId("5798abcc4d31957714ca7736"), "uniques":0, "leadPrice":0, "revenue":0, "registrations":2, "hits":10 }, ], revenue: 0, registrations: 2, hits: 44, "__v":3 }{ "_id":ObjectId("5798a25e213c708b793ed04b"), "subid":"google", "extrasubid":[ { "subid":"google", "_id":ObjectId("5798a282213c708b793ed04d"), "leadPrice":0, "revenue":0, "registrations":0, "hits":9 } ], revenue: 0, registrations: 2, hits: 9, "__v":1 } How I try to do this:
Channel.aggregate([ { $unwind: "$extrasubid" }, { $project: { _id: "$id", subid: "$subid", hits: { $sum: "$extrasubid.hits"}, registrations: { $sum: "$extrasubid.registrations"}, revenue: { $sum: "$extrasubid.revenue"}, leadPrice: { $sum: "$extrasubid.leadPrice"}, uniques: { $sum: "$extrasubid.uniques"} }}, ], function (err, results) { console.log(results, results.length); }) But at the output I get 3 objects, that is, everything is grouped by "extrasubid._id", and not just "_id". How to fix it and get the result as above?