I am currently trying to find a way to find the closest record date in mongoDB for the search I am looking for.
I have currently solved the problem using 2 queries. One of them uses $ gte and limit (1) to search for the next larger date, and then $ lte-limit (1) to see if there is anything closer to what might be lower.
I was wondering if it is possible to find the nearest date in only one query, but could not find anything in this regard.
I hope you can help me, or at least tell me that this is the only way to do this.
db.collection.find({"time":{$gte: isoDate}}).sort({"time":1}).limit(1) db.collection.find({"time":{$lte: isoDate}}).sort({"time":-1}).limit(1)
But I'm looking for a way to do this in one query, so I donβt need to subtract the results to find the closest one.
source share