Database

db={cars:[{_id:ObjectId("649d0bae47fa0b4db69f2cf6"),name:"a"},{_id:ObjectId("649d0bae47fa0b4db69f2cf8"),name:"b"},{_id:ObjectId("649d0bae47fa0b4db69f2cf9"),name:"c"}],carinfos:[{"car":ObjectId("649d0bae47fa0b4db69f2cf6"),"address":{"location":{"type":"Point","coordinates":[16.158190,39.403401]}},"timestamp":ISODate("2023-07-10T13:29:54.064Z"),},{"car":ObjectId("649d0bae47fa0b4db69f2cf6"),"address":{"location":{"type":"Point","coordinates":[16.158180,39.403421]}},"timestamp":ISODate("2023-07-09T13:29:54.064Z"),},{"car":ObjectId("649d0bae47fa0b4db69f2cf8"),"address":{"location":{"type":"Point","coordinates":[16.158190,39.403401]}},"timestamp":ISODate("2023-07-10T13:29:54.064Z"),},{"car":ObjectId("649d0bae47fa0b4db69f2cf8"),"address":{"location":{"type":"Point","coordinates":[16.158180,39.403421]}},"timestamp":ISODate("2023-07-09T13:29:54.064Z"),},{"car":ObjectId("649d0bae47fa0b4db69f2cf9"),"address":{"location":{"type":"Point","coordinates":[16.0297855,39.45938]}},"timestamp":ISODate("2023-07-10T13:29:54.064Z"),},{"car":ObjectId("649d0bae47fa0b4db69f2cf9"),"address":{"location":{"type":"Point","coordinates":[16.158180,39.403421]}},"timestamp":ISODate("2023-07-09T13:29:54.064Z"),}]}

Query

db.carinfos.aggregate([{$lookup:{from:"cars",localField:"car",foreignField:"_id",as:"carDetail"}},{$match:{$expr:{$in:[{$first:"$carDetail.name"},["a","c"]]}}},{$lookup:{from:"carinfos",localField:"car",foreignField:"car",as:"last_id",pipeline:[{$project:{_id:0,timestamp:1}},{$sort:{timestamp:-1}},{$limit:1}]}},{$match:{$expr:{$eq:[{$first:"$last_id.timestamp"},"$timestamp"]}}},])

Result