Is it possible to query for a specific date ?
I found in the mongo Cookbook that we can do it for a range Querying for a Date Range Like that :
db.posts.find({"created_on": {"$gte": start, "$lt": end}})
But is it possible for a specific date ? This doesn't work :
db.posts.find({"created_on": new Date(2012, 7, 14) })
Have you tried:
The problem you're going to run into is that dates are stored as timestamps in Mongo. So, to match a date you're asking it to match a timestamp. In your case I think you're trying to match a day (ie. from 00:00 to 23:59 on a specific date). If your dates are stored without times then you should be okay. Otherwise, try specifying your date as a range of time on the same day (ie. start=00:00, end=23:59) if gte doesn't work.
similar question
Yeah, Date object complects date and time, so comparing it with just date value does not work.
You can simply use the $where operator to express more complex condition with Javascript boolean expression :)
created_on
is the datetime field and2012-07-14
is the specified date.Date should be exactly in YYYY-MM-DD format.
Note: Use
$where
sparingly, it has performance implications.You can use following approach for API method to get results from specific day:
We had an issue relating to duplicated data in our database, with a date field having multiple values where we were meant to have 1. I thought I'd add the way we resolved the issue for reference.
We have a collection called "data" with a numeric "value" field and a date "date" field. We had a process which we thought was idempotent, but ended up adding 2 x values per day on second run:
We only need 1 of the 2 records, so had to resort the javascript to clean up the db. Our initial approach was going to be to iterate through the results and remove any field with a time of between 6am and 11am (all duplicates were in the morning), but during implementation, made a change. Here's the script used to fix it:
and then ran it with
mongo thedatabase fixer_script.js
For those of us using Moment.js
Important: all moments are mutable!
tomorrow = today.add(1, 'days')
does not work since it also mutatestoday
. Callingmoment(today)
solves that problem by implicitly cloningtoday
.That should work if the dates you saved in the DB are without time (just year, month, day).
Chances are that the dates you saved were
new Date()
, which includes the time components. To query those times you need to create a date range that includes all moments in a day.