i want to search a date like the following:
09-11
03-22
and it will search in the available documents and bring the matched documnet. an available document example :
2022-09-11T15:31:25.083 00:00
how can i do this?
i tried following query but that didn't work:
db.users.find({ createdAt: new RegExp('09-11') }) // Null
CodePudding user response:
Using aggregate
you can extract $dayOfMonth
and $month
from initial date, filter using$match
and after $project
the initial document by excluding calculated day and month from the document.
db.users.aggregate([
{
$addFields: {
month: {
$month: "$createdAt"
},
day: {
$dayOfMonth: "$createdAt"
},
}
},
{
$match: {
month: 9,
day: 11
}
},
{
$project: {
month: 0,
day: 0
}
}
])
CodePudding user response:
You can do it with aggregate
query:
$toString
- to convert date to string$regexMatch
- to apply regex search
db.collection.aggregate([
{
"$match": {
"$expr": {
"$regexMatch": {
"input": {
"$toString": "$createdAt"
},
"regex": "09-11"
}
}
}
}
])