nak
nak

Reputation: 3137

Finding document based on date range works in the mongodb shell, but not with pymongo

On the mongo shell this returns a document just fine:

> db.orderbook_log.findOne({'time': { '$gte': new Date(2014, 9, 24, 17, 38, 20, 546000), '$lt': new Date(2014, 10, 24, 17, 39, 20, 546000)}})

    //... returns document with this time stamp:
    "time" : ISODate("2014-10-25T00:47:30.819Z")

Notice I used "9" for October because JavaScript's months are 0-11. And I also tested with "23" as the day because it looks like JS days are also 0-indexed, and that also returned a document: "time" : ISODate("2014-10-24T17:32:13.595Z")

atime = datetime.datetime(2014, 10, 24, 17, 38, 20, 546000)
btime =  datetime.datetime(2014, 10, 24, 17, 39, 20, 546000)

future_book = log.find_one({"time": {"$gte": atime, "$lt": btime}})

But when I execute find_one in pymongofuture_book is None

All I'm really trying to do is loop though the first 100 records or so and get a record that occurred a relative minute later.

Upvotes: 2

Views: 695

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24009

Javascript days are not zero-indexed, alas. Only months are.

I see in your Javascript you're adding 546,000 ms to the first date, so that results in 2014-10-24 at 17:48:26. Javascript then converts to your local timezone, so in my case it adds 5 hours:

> new Date(2014, 10, 24, 17, 39, 20, 546000)
ISODate("2014-11-24T22:48:26Z")

This is then compared (ignoring timezones) with the "time" field in your documents.

Better to remove the final milliseconds argument, and use the MongoDB shell's ISODate function, which is designed to be more rational than Javascript Dates:

> ISODate('2014-10-24T17:38:20')
ISODate("2014-10-24T17:38:20Z")

That will then compare to your documents in the way you expect, and it should match the PyMongo behavior. I suggest you drop the milliseconds argument from your Python datetime constructors, too, to clarify things.

Upvotes: 2

Related Questions