databasemongodbmongoosedatefilter

Date and Time filter working fine with find() operation but issues with $match with aggregate in mongodb


I am building dynamic query as follow:

           if(DateX && DateY){
                query.createdAt = {
                    $gte: new Date(DateX).toISOString(),
                    $lt : new Date(DateY).toISOString() 
                }

            }else if(DateX){
                query.createdAt = {
                    $gte: new Date(DateX).toISOString() 
                }

            }else if(DateY){
                query.createdAt = {
                    $lt: new Date(DateY).toISOString() 
                }
            }

Here my dates DateX and DateY are dates in tz format.

Above query working fine with find() as below and returns desired results:

Model.find(query).lean().exec();

But the same query is not working with aggregate.match(query) as follow:

Model.aggregate()
            .match(query)
            .exec()

Solution

  • I was trying to convert new Date(DateX) and new Date(DateY) to ISO format date-time string which was not working here. As new Date() constructor itself returns the ISODate with the specified date.

    I just removed the .toISOString() from new Date().toISOString() and it started working fine.

    As per the mongodb official doc says: