Find the nearest date in one query

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.

+5
source share
1 answer

check this

 db.collection.find({"time":{$gte: isoDate,$lt: isoDate}}).sort({"time":1}).limit(1) 

Please use the same format that mongodb supports, e.g. followiong

 ISODate("2015-10-26T00:00:00.000Z") 
+4
source

Source: https://habr.com/ru/post/1234535/


All Articles