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-01T09:00:00Z")},{/** should be contained within group 3*/"start":ISODate("2024-01-01T06:00:00Z"),"end":ISODate("2024-01-01T08:00:00Z")}]
Query
db.collection.aggregate([{"$setWindowFields":{"sortBy":{"start":1},"output":{"prevMax":{"$max":"$end","window":{"documents":["unbounded",-1]}}}}},{$set:{isStart:{$lt:["$prevMax","$start"]}}},{"$setWindowFields":{"sortBy":{"start":1},"output":{"grouping":{"$max":{"$cond":{"if":{"$eq":[true,"$isStart"]},"then":"$start","else":-1}},"window":{"documents":["unbounded","current"]}}}}},{"$group":{_id:"$grouping",end:{$max:"$end"}}},{"$project":{_id:0,start:"$_id",end:1}}])