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 o
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()
}
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}}
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")}}
]
})
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")}
})
Updated 2018-06-26 fixed up the code to use moment() instead of new Date()
So it sounds like there is no mongodb equivalent to MySQL's DATE
function, like with SELECT col1, col2 FROM table WHERE DATE(date_field) = DATE(NOW())
In lieu of a native solution, I solved this by use MomentJS Timezone (http://momentjs.com/timezone/) to convert the date/time to a date-only numerical field, then I store the date as a number.
In my javascript code (outside of MongoDB):
var localDateOnly = function(timezone, d) {
if (d == undefined) { d = new Date(); } // current date/time
return Number( moment(d).tz(timezone).format("YYYYMMDD") );
}
Then I store a date-only field in the Mongo record.
var myDate = localDateOnly("America/New_York"); // today, in YYYYMMDD number
db.birthdays.insert(
{ dateonly: myDate, event: "This day is my birthday!" }
);
Then in my Javascript code, I can easily query today, tomorrow, specific days, etc.
// today
var myDate = localDateOnly("America/New_York");
db.birthdays.find( { dateonly: myDate } );
// tomorrow
var myDate = localDateOnly(
"America/New_York",
moment().add( 1, "days" )
); // tomorrow
db.birthdays.find( { dateonly: myDate } );
// someone wants to know birthdays on the calendar on July 15, 2015
// regardless which time zone they are in
// just find the date in YYYYMMDD format
db.birthdays.find( { dateonly: 20150715 } );
Hope this helps someone. It's storing a number, not a string, on purpose to improve performance on its index. I have other code which enforces a valid-looking number, before storing into the database it checks:
moment( 20150715, "YYYYMMDD", true ).isValid() // returns true & allowed to store in the database
moment( 150715, "YYYYMMDD", true ).isValid() // returns false, don't insert into db