简体   繁体   中英

Mongodb :: Find data between two dates

I have a simple use case. I want to extract data between two dates. Let say I have the only below document in my collection.

{
    
    "fromDate": "2022-07-07T00:00:00.000+00:00"
    "toDate": "2022-12-12T11:59:59.999+00:00",
    "promotionName": "Ticket discount"
}

I am applying below query it works fine as long as dates are exactly matched. But in case of dates between fromDate and toDate it gets failed.

busTicketPromotions.find({
    fromDate : {'$gte': new Date(fromDate)}, 
    toDate : {'$lte': new Date(toDate) }, 
});

Suppose if I pass 2022-07-07T00:00:00.000+00:00 in fromDate and 2022-12-12T11:59:59.999+00:00 in toDate, i get the result.

But if I pass 2022-08-08T00:00:00.000+00:00 in fromDate and 2022-11-11T11:59:59.999+00:00 in toDate it gets failed.

In simple words I want results equals to or between fromDate and toDate .

What am I doing wrong ?

You have to turn the date into ISODate like this:

busTicketPromotions.find({
        day: {
            $gt: ISODate("2020-01-21"),
            $lt: ISODate("2020-01-24")
        }
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM