DEV Community

Discussion on: How to query documents in MongoDB that fall within a specified date range using Mongoose and Node.

Collapse
 
asharlohmar profile image
Lohmar ASHAR • Edited

Actually that query is not exactly correct... in this form you will be missing 1 second worth of data... all the records between the 23:59:59 of the endDate and the 00:00:00 of the next day

If you want you're search to be "endDate day inclusive" than you should add a day to the endDate and use $lt with the 00:00:00 of that date, otherwise you should stick with a "endDate day exclusive" search and use the 00:00:00 of the endDate for the $lt part of the query (just make sure that user knows that).

Another point you should've made present (hope this is English enough) would be that this is the only correct way to do a search for a value in an interval, be it for Date or other datatype, and that a query like:

{ 
 date_paid: { $gte: <some date>}, 
 date_paid: { $lt: <some other date>}
}
Enter fullscreen mode Exit fullscreen mode

would produce other (unexpected and undesired) results.
Later edit: actually now I have to make sure if this is true, but I'm very confident that it is.
Later-later edit: actually I was right. You can see some sample tests here (for the query in the right way) and here (for the query in the "wrong form"/that produces the undesired results).
Side note: actually, if you think about it, making the search "endDate day inclusive" is pretty counter-intuitive from a user-experience point of view, if you'd want to get a day's worth of data you'd have to set both the startDate and endDate to the same value ... just my 2 cents.