Database

[{"_id":{"$oid":"5e34522580e513373d96112b"},"productId":{"$oid":"5e345223b3aa703b8a9a4f34"},"createdAt":{"$date":"2018-03-04T06:19:36.346Z"},},{"_id":{"$oid":"5e34522580e513373d9611e3"},"productId":{"$oid":"5e345223b3aa703b8a9a4f34"},"createdAt":{"$date":"2018-03-04T06:19:36.346Z"},},{"_id":{"$oid":"5e34522580e513373d9611fa"},"productId":{"$oid":"5e345223b3aa703b8a9a4f35"},"createdAt":{"$date":"2018-03-04T06:19:36.346Z"},},{"_id":{"$oid":"5e34522580e513373d96123c"},"productId":{"$oid":"5e345223b3aa703b8a9a4f35"},"createdAt":{"$date":"2018-03-04T06:19:36.346Z"},}]

Query

db.collection.aggregate([{$group:{_id:{createdAt:{$dateToString:{format:"%Y-%m-%d",date:"$createdAt"}},productId:"$productId"},count:{$sum:1}}},{$group:{_id:"$_id.createdAt",products:{$push:{productId:"$_id.productId",count:"$count"}}}},{"$replaceRoot":{"newRoot":{"$mergeObjects":[{_id:"$_id"},{$arrayToObject:{$map:{input:"$products",in:{k:{$toString:"$$this.productId"},v:"$$this.count"}}}}]}}}])

Result