DEV Community

Cover image for How to query documents in MongoDB that fall within a specified date range using Mongoose and Node.

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

Audiophile on November 07, 2019

Please Note: This tutorial assumes you have a working knowledge of javascript, the node run-time environment, mongoose queries and mongoDB ...
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.

Collapse
 
mrshadowgames profile image
MrShadowGames

Call me picky, but I prefer sticking with the same syntax that I use in direct queries to a MongoDB:

Instead of

date_paid: {
        $gte: new Date(new Date(startDate).setHours(00, 00, 00))
        $lt: new Date(new Date(endDate).setHours(23, 59, 59))
         }

Enter fullscreen mode Exit fullscreen mode

(Also, I wonder if that actually works, since there is a comma missing)

I'd use:

$and: [{ date_paid: { $gte: ... } }, { date_paid: { $lt: ... } }]
Enter fullscreen mode Exit fullscreen mode

But again, it's me probably just being notoriuosly picky

Collapse
 
monfernape profile image
Usman Khalil

I was recently facing the very same problem. You made it quite clear

Collapse
 
itz_giddy profile image
Audiophile

I'm glad it helped!

Collapse
 
rabbyhossain profile image
Rabby Hossian

Great article

Collapse
 
divee789 profile image
Divine Olokor

Please can someone provide the client side implementation please