Search code examples
pythonpymongo

how to query using isodate in pymongo


I have a mongodb query that works in the mongo shell:

db.collection.find({ created_at:  { $gte : ISODate("2015-03-01T00:00:00.000Z"), $lt : ISODate("2015-03-30T00:00:00.00Z") } })

I'm trying the following pymongo:

test_range = agents.coll.find({ "created_at" :  { "$gte" : "ISODate('2015-03-01T00:00:00.000Z')", "$lt" : "ISODate('2015-03-30T00:00:00.00Z')" } })

and I'm getting SyntaxError: invalid syntax

What the correct way to handle ISODate in pymongo query?


Solution

  • Dates are stored as ISODates in MongoDB but, when you're using Pymongo, dates are converted to Python Datetime objects. So, using Pymongo, your query should look like this:

    test_range = agents.coll.find({ "created_at": {"$gte" : datetime(2015, 3, 1), "$lt": datetime(2015, 3, 30)}})