I have documents in a collection with date format
updated: 2022-10-25T05:04:47.904+00:00
How to modify the query to get the count for today’s date
const today = new Date()
....
await db.collection('posts').countDocuments({"updated": today})
I have documents in a collection with date format
updated: 2022-10-25T05:04:47.904+00:00
How to modify the query to get the count for today’s date
const today = new Date()
....
await db.collection('posts').countDocuments({"updated": today})
2
Answers
This works but not sure if its the best way. Seems complicated for a simple task to match date.
So set hours to 0000 and then check for documents greater than that. So everyday, new Date() will be today and this will only show documents from today.
With MongoDB v5.0+,
Use
$dateTrunc
withunit: "day"
to perform date-only comparison.(i.e. without time part). You can use built-in$$NOW
variable to get today’s date.Mongo Playground
With MongoDB v4.0+,
you can rely on comparing 2 integer division result of
updated
and$$NOW
to get today’s record.Mongo Playground