I want to filter with a regex on date. I tried this:
{ createdAt: { $regex: '2021-06-25T' }}
But it doesn't work.
How can I use a regex or something to filter for those days, on a timeStamp
field?
The collections looks like this:
But the original JSON shows this:
{
"_id": {
"$oid": "60d635cb26bec4004fb19341"
},
"createdAt": {
"$date": {
"$numberLong": "1624651211668"
}
},
"__v": 0
}
CodePudding user response:
If you want to keep everything as Dates and find documents for that specific day, you could try this.
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
{
"$dateTrunc": {
"date": "$createdAt",
"unit": "day"
}
},
ISODate("2021-06-25T00:00:00Z")
]
}
}
}
])
Try it on mongoplayground.net.
CodePudding user response:
You should convert the date to a string version and then apply the match. Try something like this:
db.collection.aggregate([
{
"$match": {
$expr: {
"$regexMatch": {
"input": {
"$toString": "$createdAt"
},
"regex": "2021-06-25T"
}
}
}
}
])