Database
[{"_id":"1","type":"start","datetime":ISODate("2022-02-01T10:15:00Z"),"userId":"1"},{"_id":"2","type":"end","datetime":ISODate("2022-02-01T10:20:00Z"),"userId":"1"},{"_id":"3","type":"start","datetime":ISODate("2022-02-01T10:16:00Z"),"userId":"2"},{"_id":"4","type":"end","datetime":ISODate("2022-02-01T10:21:00Z"),"userId":"2"},{"_id":"5","type":"start","datetime":ISODate("2022-02-02T11:01:00Z"),"userId":"1"},{"_id":"6","type":"end","datetime":ISODate("2022-02-02T11:02:00Z"),"userId":"1"}]
Query
db.collection.aggregate([{/** add winField sorted array to each doc* containing userId docs following* current doc*/"$setWindowFields":{"partitionBy":"$userId","sortBy":{"datetime":1},"output":{"winField":{"$push":"$$CURRENT","window":{"documents":[1,"unbounded"]}}}}},{/** just keep start docs*/"$match":{"type":"start"}},{/** sorting on start datetime*/"$sort":{"datetime":1}},{/** output desired fields*/"$project":{"_id":0,"userId":1,"started_at":"$datetime","end_at":{/** grab first end datetime*/"$getField":{"field":"datetime","input":{"$first":{"$filter":{"input":"$winField","cond":{"$eq":["$$this.type","end"]}}}}}}}}])