Database

db={"collection":[{"_id":"5e0ae793b1384737a4f855cf","template":"13435158964","deviceId":"a-1","heat":30,"humidity":40},{"_id":"5e0ae7a2b1384737a4f855d0","template":"13435158964","deviceId":"sb-0001","heat":40,"humidity":20},{"_id":"5e0ae890b1384737a4f855d3","template":"13435158964","deviceId":"a-1","heat":10,"humidity":20},{"_id":"5e0af188981f39410cd89b73","template":"13435158964","deviceId":"a-1","heat":60,"humidity":50},{"_id":"5e0af196981f39410cd89b74","template":"13435158964","deviceId":"sb-0001","heat":15,"humidity":25}],"templates":[{"_id":"5e0ae38729218b0a3861118b","templateId":"13435158964","devices":[{"deviceId":"a-1","_id":"5e0ae49629218b0a3861118f","group":"5e0ae41d29218b0a3861118d",},{"deviceId":"sb-0001","_id":"5e0af166981f39410cd89b72","group":"5e0af11d981f39410cd89b70"}]}],"groups":[{"_id":"5e0af11d981f39410cd89b70","template":"5e0ae38729218b0a3861118b","groupName":"Flats"},{"_id":"5e0ae41d29218b0a3861118d","template":"5e0ae38729218b0a3861118b","groupName":"Swimming Pool"}]}

Query

db.collection.aggregate([{$lookup:{from:"templates",localField:"template",foreignField:"templateId",as:"templateData"}},{$unwind:"$templateData"},{$unwind:"$templateData.devices"},{$match:{$expr:{$eq:["$deviceId","$templateData.devices.deviceId"]}}},{$lookup:{from:"groups",localField:"templateData.devices.group",foreignField:"_id",as:"groupData"}},{$unwind:"$groupData"},{$group:{_id:"$groupData.groupName",heat:{"$sum":"$heat"},humidity:{"$sum":"$humidity"},count:{"$sum":1}}}])

Result