Database
db={"suggestions":[{"_id":ObjectId("5e7d7bf7d86d85088863f4de"),"channelId":"23435553",},],"emotes":[{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"emoteId":"A",},{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"emoteId":"A",},{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"emoteId":"B",},],"bounties":[{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"userId":"user1","bountyAmount":50,},{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"userId":"user1","bountyAmount":100,},{"suggestionId":ObjectId("5e7d7bf7d86d85088863f4de"),"userId":"user2","bountyAmount":200,},]}
Query
db.suggestions.aggregate([{$match:{"channelId":"23435553"}},{$lookup:{from:"emotes",localField:"_id",foreignField:"suggestionId",as:"emotes"}},{$unwind:{path:"$emotes",preserveNullAndEmptyArrays:true}},{$group:{_id:{"_id":"$_id","emoteId":"$emotes.emoteId"},channelId:{$first:"$channelId"},count:{$sum:1}}},{$group:{_id:"$_id._id",channelId:{$first:"$channelId"},emotes:{$push:{k:"$_id.emoteId",v:"$count"}}}},{$lookup:{from:"bounties",localField:"_id",foreignField:"suggestionId",as:"bounties"}},{$unwind:{path:"$bounties",preserveNullAndEmptyArrays:true}},{$group:{_id:{"_id":"$_id","userId":"$bounties.userId"},channelId:{$first:"$channelId"},emotes:{$first:"$emotes"},bountyAmount:{$sum:"$bounties.bountyAmount"}}},{$group:{_id:"$_id._id",channelId:{$first:"$channelId"},emotes:{$first:"$emotes"},bounties:{$push:{k:"$_id.userId",v:"$bountyAmount"}}}},{$project:{_id:1,channelId:1,emotes:{$arrayToObject:"$emotes"},bounties:{$arrayToObject:"$bounties"},}}])