In a MongoDB database, I have a collection of items, and each item stores its creation date. I need to query this collection by date. I tried:
db.items.findOne({date:{new Date(1285947037*1000)}})
but it isn’t returning anything. I got that timestamp using PHP ($date->sec, where $date is a MongoDate object from the database). So what’s the right way to do this? Thanks.
The
Dateconstructor expects a timestamp in milliseconds. The1285947037timestamp is in seconds, which is why you’re multiplying it by 1000.My guess is that the actual timestamp in the document contains milliseconds, e.g.
1285947037461(note the 461 at the end). You’re multiplying the seconds by 1000, which results in1285947037000. As you can see, these timestamp aren’t equal:The problem lies with the
MongoDateclass: it loses the milliseconds precision, as you can read in the documentation. Here’s the quote:To find the document you’re looking for using the timestamp in seconds, you need something like this:
You can get the exact timestamp in milliseconds in the console, by using
myDateObject.getTime().