We have a collection with multiple documents ordered with respect to a given timestamp. We want to aggregate documents between two timestamps (let’s say startTime and stopTime): that is a simple match stage in our aggregation that has a query such as timestamp: {$gte: startTime, $lte: stopTime}. However, we’d like to include two extra documents in the result of this step: the closest document right before startTime, no matter how far back in time we would need to look, and also the closest document right after stopTime. Is there a way to achieve this with the aggregation framework in MongoDB?
2
Answers
One option if you are already after filtering out these documents, is using a
$lookup
step with a pipeline. It looks a bit clumsy after the$lookup
s, but I could not think about another way to continue without grouping all the documents, which is not the best way to go.$match
– This is a "fake" step in order to level up with your situation. You already have it in your current pipeline, thus don’t need it here$set
the "$$ROOT" in order to use it latter$lookup
twice in order to get your requested documents from the original collectionbefore
andafter
out of the current documents$unwind
to separate into documents$group
by_id
in order to remove the duplicates of thebefore
andafter
documentsSee how it works on the playground example
Chain up
$unionWith
with$sort
and$limit: 1
to get the documents out of range.Here is the Mongo Playground for your reference.