Database
db={"users":[{"_id":"user1","name":"John"},{"_id":"user2","name":"Jane"},{"_id":"user3","name":"Mike"},{"_id":"user4","name":"Anna"},{"_id":"user5","name":"Tom"}],"files":[{"_id":"fileID1","url":"url1","userID":"user1","at":197},{"_id":"fileID2","url":"url2","userID":"user1","at":719},{"_id":"fileID3","url":"url3","userID":"user1","at":280},{"_id":"fileID4","url":"url4","userID":"user1","at":773},{"_id":"fileID7","url":"url7","userID":"user2","at":486},{"_id":"fileID8","url":"url8","userID":"user2","at":749},{"_id":"fileID9","url":"url9","userID":"user2","at":600},{"_id":"fileID10","url":"url10","userID":"user2","at":397},{"_id":"fileID11","url":"url11","userID":"user2","at":915},{"_id":"fileID12","url":"url12","userID":"user2","at":849},{"_id":"fileID13","url":"url13","userID":"user3","at":814},{"_id":"fileID14","url":"url14","userID":"user3","at":587},{"_id":"fileID15","url":"url15","userID":"user3","at":406},{"_id":"fileID16","url":"url16","userID":"user3","at":382},{"_id":"fileID17","url":"url17","userID":"user3","at":196},{"_id":"fileID19","url":"url19","userID":"user4","at":983},{"_id":"fileID20","url":"url20","userID":"user4","at":547},{"_id":"fileID21","url":"url21","userID":"user5","at":810},{"_id":"fileID22","url":"url22","userID":"user5","at":283},{"_id":"fileID23","url":"url23","userID":"user5","at":339},{"_id":"fileID24","url":"url24","userID":"user5","at":818},{"_id":"fileID25","url":"url25","userID":"user5","at":152},{"_id":"fileID26","url":"url26","userID":"user5","at":170},{"_id":"fileID27","url":"url27","userID":"user5","at":125}]}
Query
db.files.aggregate([{$match:{userID:{$in:["user1","user2","user5"]}}},{$group:{_id:"$userID",v:{$push:{id:"$_id",at:"$at"}}}},{$project:{v:{$map:{input:{$slice:[{$sortArray:{input:"$v",sortBy:{at:-1}}},5]},in:"$$this.id"}}}},{$group:{_id:null,kv:{$push:{k:"$_id",v:"$v"}}}},{$replaceRoot:{newRoot:{$arrayToObject:"$kv"}}}])