Database

[{_id:ObjectId("5c05984246a0201286d4b57a"),timestamp:ISODate("2022-10-16T12:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b57b"),timestamp:ISODate("2022-10-15T10:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b57c"),timestamp:ISODate("2022-10-14T12:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b57d"),timestamp:ISODate("2022-10-13T12:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b57e"),timestamp:ISODate("2022-10-12T12:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b57f"),timestamp:ISODate("2022-10-11T12:00:12.000Z")},{_id:ObjectId("5c05984246a0201286d4b570"),timestamp:ISODate("2022-10-10T12:00:12.000Z")}]

Query

db.collection.aggregate([{$match:{timestamp:{$gte:ISODate("2022-10-13T14:00:12Z"),$lte:ISODate("2022-10-15T10:00:12Z")}}},{$set:{data:"$$ROOT"}},{$lookup:{from:"collection",let:{},pipeline:[{$match:{timestamp:{$lt:ISODate("2022-10-13T14:00:12Z")}}},{$sort:{timestamp:-1}},{$limit:1}],as:"before"}},{$lookup:{from:"collection",let:{},pipeline:[{$match:{timestamp:{$gt:ISODate("2022-10-15T10:00:12Z")}}},{$sort:{timestamp:1}},{$limit:1}],as:"after"}},{$project:{_id:0,data:{"$concatArrays":["$after","$before",["$data"]]}}},{$unwind:"$data"},{$group:{_id:"$data._id",data:{$first:"$data"}}},{$replaceRoot:{newRoot:"$data"}},{$sort:{timestamp:1}},])

Result