Database
[{/** group 1*/"start":ISODate("2024-01-01T00:00:00Z"),"end":ISODate("2024-01-01T01:00:00Z")},{/** group 1*/"start":ISODate("2024-01-01T01:00:00Z"),"end":ISODate("2024-01-01T02:00:00Z")},{/** group 2*/"start":ISODate("2024-01-01T03:00:00Z"),"end":ISODate("2024-01-01T04:00:00Z")},{/** group 3*/"start":ISODate("2024-01-01T05:00:00Z"),"end":ISODate("2024-01-01T06:00:00Z")},{/** group 3*/"start":ISODate("2024-01-01T06:00:00Z"),"end":ISODate("2024-01-01T07:00:00Z")},{/** group 3*/"start":ISODate("2024-01-01T07:00:00Z"),"end":ISODate("2024-01-01T09:00:00Z")}]
Query
db.collection.aggregate([{"$setWindowFields":{"sortBy":{"start":1},"output":{"prevMax":{"$push":"$end","window":{"documents":[-1,0]}},"nextMin":{"$push":"$start","window":{"documents":[0,1]}}}}},{$match:{$or:[{$expr:{$lt:[{$first:"$prevMax"},"$start"]}},{$expr:{$gt:[{$last:"$nextMin"},"$end"]}},{"prevMax.1":{$exists:false}},{"nextMin.1":{$exists:false}}]}},{$set:{isStart:{$or:[{$lt:[{$first:"$prevMax"},"$start"]},{$eq:[{$size:"$prevMax"},1]}]}}},{"$setWindowFields":{"sortBy":{"start":1},"output":{"grouping":{"$max":{"$cond":{"if":{"$eq":[true,"$isStart"]},"then":"$start","else":-1}},"window":{"documents":[-1,0]}}}}},{"$group":{_id:"$grouping",end:{$max:"$end"}}},{"$project":{_id:0,start:"$_id",end:1}}])