$lte not working as expected

I want to perform a query that allows me to find all the objects existing in the collection within certain dates including the boundary dates.

Let’s assume that the date range is 2022-11-01 and 2022-11-03, the query would be

{created: {'$gte': new Date('2022-11-01'), '$lte': new Date('2022-11-03')}}

By doing the query this way, I only get results that are greater than or equal to “2022-11-01” and lower than “2022-11-03”. Meaning that, even if I’m performing an $lte query, I always get the $lt results.
So how do i proceed if i want even the boundary date

Hi @sai_sankalp

I did a quick test and it seems to work correctly in MongoDB 6.0.2:

> db.test.find({created: {'$gte': new Date('2022-11-01'), '$lte': new Date('2022-11-03')}})
[
  { _id: 0, created: ISODate("2022-11-01T00:00:00.000Z") },
  { _id: 1, created: ISODate("2022-11-03T00:00:00.000Z") }
]

What I think happened is that your date needs to be exactly 2022-11-03T00:00:00.000Z for it to be included in the result. With real world data this might be tricky, especially if you’re recording the date right down to the millisecond. If you can test it yourself, you can perhaps insert a document with the exact value of 2022-11-03T00:00:00.000Z and see if it’s included in the result or not.

If you’re still having issues with this, please provide the output you’re seeing, along with example documents that you think should be included in the output. Please also provide your MongoDB version.

Best regards
Kevin

2 Likes

Thanks @kevinadi,let me check that and reply back