How to find Mongo records before and after a specific time in a single query

I have a collection where I have a timestamp field and several records. Now I am trying to make a single query where I put a request time as input param it should just return me the record which is immediately before and after that request time.

For example, say there is 1 record for each day from 13-SEP till 22-SEP and I pass 18-SEP as request date then it should return me 17-SEP and 19-SEP records only.

Is it possible to do in MongoDB and if so how??

My approach would be to

  1. $sort on the date
  2. have a $facet with 2 pipelines
    2a. One facet would $match $lt pivot date and keep $last of the $group
    2b. The other facet would $match $gt pivot date and keep $first of the $group
2 Likes