How to write a query or a aggregation in mongo DB like below
select *
from final
where Week=month(todaysdate())+"-"+day(todaysdate())+"-"+year(todaysdate()))
How to write a query or a aggregation in mongo DB like below
select *
from final
where Week=month(todaysdate())+"-"+day(todaysdate())+"-"+year(todaysdate()))
Assume the following document in the database:
{ "_id" : ObjectId("614ce00e6db392727c999e7f"), "Week" : "09-23-2021" }
Here is an aggregation...
db.collection.aggregate([
{
$project:
{
Week:
{
$dateFromString:
{
dateString: "$Week",
format: "%m-%d-%Y"
}
}
}
},
{
$match: { $expr: { $eq: [ "$Week", { $dateFromParts: {"year": new Date().getFullYear(), "month": new Date().getMonth() + 1, "day": new Date().getDate() } } ] } }
}
])
Explanation
First Stage: $Project - interpret the date string in a way we can use a legit ISODate() object for comparisons. Use the $dateFromString expression to convert the field text data to an ISODate().
Second Stage: $Match - use the $expr expression operator to compare the field path variable $Week with the current date by composing a date without a timestamp portion. Match and return those with an equality match.
Caution
the date method getMonth() is always off by 1 as expected by a human. January is month zero. For this reason, to match your expected date string a +1 is added to the aggregation.
Assumptions
Recommendations
Store your date data as an ISODate() not as a string, then use a range query to find data elements between two distinct points in time. If you are interested in a whole day, then the range should be midnight on the first date (inclusive) and midnight on the second day(exclusive). Make sure you have an index on the field for the range query to work efficiently. Watch out for timezone stuff. Mongo likes to store everything in UTC.