Database

[{"_id":"1","interactionType":"pageEnter","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0","occurredAt":"2020-06-12T17:00:22.000Z"},{"_id":"2","interactionType":"pageExit","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0","occurredAt":"2020-06-12T17:00:32.000Z"},{"_id":"3","interactionType":"pageEnter","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0/a","occurredAt":"2020-06-12T17:00:42.000Z"},{"_id":"4","interactionType":"pageExit","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0/a","occurredAt":"2020-06-12T17:00:52.000Z"},{"_id":"5","interactionType":"pageEnter","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0","occurredAt":"2020-06-12T17:03:42.000Z"},{"_id":"6","interactionType":"pageExit","uid":"u0","documentId":"d0","clientType":"web","routePath":"/d0","occurredAt":"2020-06-12T17:03:52.000Z"}]

Query

db.collection.aggregate([/** Filter by pageEnter and pageExit*/{$match:{interactionType:{$in:["pageEnter","pageExit"]}}},/** Sort by occurredAt*/{$sort:{occurredAt:1}},/** Group by special id and and compose history.*/{$group:{_id:{uid:"$uid",documentId:"$documentId",clientType:"$clientType",},history:{$push:"$$ROOT"},},},/** Project fields for final document.*/{$project:{_id:{$concat:["$_id.documentId","-","$_id.uid","-","$_id.clientType","-",{$arrayElemAt:["$history.occurredAt",0]}]},uid:{$arrayElemAt:["$history.uid",0]},documentId:{$arrayElemAt:["$history.documentId",0]},lastViewedAt:{$arrayElemAt:["$history.occurredAt",0]},totalDurationMilli:"unknown",history:1,},},])

Result