Database

[{"metadata":{"sensorId":5578,"type":"temperature"},"timestamp":ISODate("2021-05-18T00:00:00.000Z"),"temp":72},{"metadata":{"sensorId":5578,"type":"humidity"},"timestamp":ISODate("2021-05-18T00:00:00Z"),"humpercent":78}]

Query

db.collection.aggregate([{$sort:{timestamp:1}},{$set:{m:"$$ROOT"}},{$unset:["m.metadata","m.timestamp","m._id"]},{$set:{m:{$first:{$objectToArray:"$m"}}}},{$group:{_id:{type:"$metadata.type",sensorId:"$metadata.sensorId"},data:{$push:"$m.v"}}},{$project:{_id:0,data:1,type:{k:"type",v:"$_id.type"},sensorId:"$_id.sensorId"}},{$group:{_id:"$sensorId",data:{$push:{k:"$type.v",v:"$data"}}}},{$project:{_id:0,data:{"$mergeObjects":[{$arrayToObject:"$data"},{sensorId:"$_id"}]}}},{$replaceRoot:{newRoot:"$data"}}])

Result