I’m using the MongoDB version 4.4, I’m trying to return the last documents inserted in the last 24 hous, and i need to run this query every day, because of this, i don’t set the date manualy, I need to use new Date()
The problem is, when a put more arguments to bring me the last 24 hours, the MongoDB return a error message to me, and i try for many ways to resolve this, but nothing worked
This is my code
{
"$match" : {
"CreatedAt2" : {
"$gte" : ISODate("2022-04-21")
}
}
}
If i run this code, this works fine, but if a change the string by new Date(), the problem start.
In my test, if a put only new Date() like bellow and find by ‘$lte’, the code rans good.
‘$lte’ is only to check if new Date() will works
"CreatedAt2" : { $lte: new Date() }
So, if a tried to include the value to return the last 24 hours, my query don’t work, look bellow
"CreatedAt2" : { $gte: new Date(new Date().getTime() - 86400000) }
The MongoDB bring to me this error message
Now I don’t know what I need to do to fix this.
3
Answers
Try this
This should work fine
Consider leveraging the
$$NOW
aggregation variable and$subtract
it by 24hours * 60minutes * 60 seconds * 1000 milliseconds = 86400000 ms to get the records within 24 hoursHere is the Mongo playground for your reference.
Instead of subtracting 86400000 Milliseconds, you can also use
Or use a 3rd party date-library, e.g. moment.js