Priyesh Tiwari
Priyesh Tiwari

Reputation: 341

mongodb date range issue

My mongoose query is

var filter = {
    changeDate: { $lte: toDate, $gte: fromDate }
};
changeLog.find(filter).sort('-changeDate').exec(function (err, _doc) {
    if (err) {
        logger.error(err);
        return res.status(400).send({ isSuccess: false, message: err, data: _doc });
    }
    return res.status(200).send({ isSuccess: true, message: err, data: result });
});

fromdate is 2/7/2016 and todate is 2/8/2016 . but I am getting record for only of 7th feb date not of 8th feb. Everytime code is taking todate as &lt not as &lte

In mongo changeDate is stored like 2016-02-01 07:49:29.084Z

Upvotes: 3

Views: 69

Answers (1)

chridam
chridam

Reputation: 103475

Your date range query is essentially looking for documents whose changeDate value fall in this range

ISODate("2016-02-07 00:00:00.000Z") <= changeDate <= ISODate("2016-02-08 00:00:00.000Z")

So for your query to filter 8th of Feb documents as well, consider changing your toDate to 9th of Feb so that it will pick from this range

ISODate("2016-02-07 00:00:00.000Z") <= changeDate < ISODate("2016-02-09 00:00:00.000Z")

e.g.

var toDate = new Date("2016-02-09"),
    fromDate = new Date("2016-02-07")
    filter = { "$gte": fromDate, "$lt": toDate };

Upvotes: 1

Related Questions