Database

[{"_id":1,"timestamp":20,"value":3,"typeId":"ff","unitId":"abc"},{"_id":2,"timestamp":17,"value":2,"typeId":"ff","unitId":"fff"},{"_id":3,"timestamp":17,"value":3,"typeId":"gg","unitId":"abc"},{"_id":4,"timestamp":21,"value":5,"typeId":"gg","unitId":"fff"},{"_id":5,"timestamp":15,"value":4,"typeId":"ff","unitId":"abc"},{"_id":6,"timestamp":24,"value":2,"typeId":"gg","unitId":"abc"}]

Query

db.collection.aggregate([{$match:{unitId:"abc"}},{$sort:{typeId:1,timestamp:1}},{$group:{_id:"$typeId",latestRecord:{$last:"$$ROOT"}}}])

Result