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()
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:
new Date("") returns the ISODate with the specified date.
new Date("") specifies the datetime in the
client’s local timezone and returns the ISODate with the specified
datetime in UTC.
new Date("") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
new Date() specifies the datetime as milliseconds since
the Unix epoch (Jan 1, 1970), and returns the resulting ISODate
instance.