'find mongodb collection document with date String
I have date string like
2022-05-17
And My mongodb collection document like
{
"_id": { "$oid": "aabbccddeeff" },
"title": "test",
"content": "test",
"author": "tester",
"churchId": { "$oid": "e5eakjshuwb3546" },
"markAsRead": false,
"createdAt": { "$date": "2022-05-17T08:18:57.174Z" },
"updatedAt": { "$date": "2022-05-17T08:18:57.174Z" },
"__v": 0
}
Now How do I find this collection using date string like mention above.
I have used this query as well
.find({ churchId, createdAt: new Date(createdAt) }, ' -__v')
But couldn't work.
Solution 1:[1]
You can do something like
createdAt: {$gte: ISODate("2022-05-17T00:00:00"), $lte: ISODate("2022-05-17T23:59:59")}
It will bring all the docs falls on the given day.
Solution 2:[2]
If project environment like typescript ,then ISODate shows an error like:
'cannot find ISODate'
So we can use new Date() class like:
createdAt: {
$gte: new Date("2022-05-17T00:00:00"),
$lte: new Date("2022-05-17T23:59:59")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gibbs |
| Solution 2 | Tyler2P |
