'MongoDB comparing dates only without times
How do I query for a date field in MongoDB with the date only, and not times? For example, if MongoDB stores July 7, 2015 with any time, I want to match that day only with today's date.
In MySQL, I would do SELECT col1, col2 FROM table WHERE DATE(date_field) = DATE(NOW());
Notice how MySQL has a function to change the date_field to the date only during matching. Can I do this in MongoDB with a similar function during matching? Like Collection.find({ dateonly(datetimefield): dateonly(new Date() }); or something of the like?
I understand Mongo stores date/times in GMT, so I would also have to convert the stored GMT date+time from GMT to Local before matching the date only, but to get me started, would like to know if I can strip the time off of a date match. For example, if GMT now is July 8 at 03:00 but Local Eastern Time US is July 7 at 23:00 then I would want to match July 7.
Solution 1:[1]
I guess You should make a range query between the start of the day and its ending(or without ending if you are talking about today). Something like this
db.collection.find({
"date" : {"$gte": new Date("2015-07-07T00:00:00.000Z"),
"$lt": new Date("2015-07-08T00:00:00.000Z")}
})
Solution 2:[2]
You can extract the date as string at any given format and compare it with your date at that format using aggregation pipiline
$addFields: { "creationDate": {$dateToString:{format: "%Y-%m-%d", date: "$createdAt"}}}},
{$match : { creationDate: {$eq: req.query.date}}
Solution 3:[3]
It's possible with $expr
{ $expr: {$eq: ["2021-03-29", { $dateToString: {date: "$dateField", format: "%Y-%m-%d"}}]}}
Solution 4:[4]
This is my proposed solution:
db.collection.find({
$and: [
{"date": {$gte: new Date("2015-07-07T00:00:00.000Z")}},
{"date": {$lt: new Date("2015-07-08T00:00:00.000Z")}}
]
})
Solution 5:[5]
I did a combination of the answers of Crash_Override and Maxim_PontyUshenko. Use Moment.js and the $gt, $lt mongo operators.
ship_date: {
$lt: moment().hours(0).minutes(0).seconds(0).milliseconds(0).add(28, "days").toDate(),
$gte: moment().hours(0).minutes(0).seconds(0).milliseconds(0).toDate()
}
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 | |
| Solution 2 | Atikur Rahman Sabuj |
| Solution 3 | Liphtier |
| Solution 4 | Aphisith Keosavang |
| Solution 5 | Nate Barr |
