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.
The $dateDiff expression returns the integer difference between the startDate and endDate measured in the specified units . Durations are measured by counting the number of times a unit boundary is passed. For example, two dates that are 18 months apart would return 1 year difference instead of 1.5 years .
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
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")} })
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With