unable to Retrieve data from monog using pymongo with date query.

2,957 views
Skip to first unread message

Rakesh

unread,
Jan 29, 2015, 7:04:25 AM1/29/15
to mongod...@googlegroups.com
Hi MongoDBusers

I am using Python (pymongo) to connect to Mongodatabase 

Here are my records
{
     "_id" : ObjectId("54b78de7b5eee824b0e7911b"), 
    "VERSION" : null, 
    "CREATE_DATE" : ISODate("2014-08-04T04:29:03.000+0530"),
}
{
     "_id" : ObjectId("54b78de7b5eee824b0e7911b"), 
    "VERSION" : null, 
    "CREATE_DATE" : ISODate("2015-08-04T04:29:03.000+0530"),
}

i am unable to retrieve the records from mongo db using ISODate query which shown below

cursor = db.review.find({ "CREATE_DATE": { "$gt": ISODate("2014-01-01T00:00:00.000+0530") } })  

when i run the above query it is throwing following exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ISODate' is not defined


if i encode ISODate with double quotes i am getting output with 0 records but the query should return one record as per the above collection.
>>>cursor = db.review.find({ "CREATE_DATE": { "$gt": "ISODate("2014-01-01T00:00:00.000+0530")" } }) 
>>>cursor.count()
0

Can any one help me querying the mongodb using the above date format from python. searched in many forums but no luck. 

Regards
Rakesh



Will Berkeley

unread,
Jan 29, 2015, 10:50:54 AM1/29/15
to mongod...@googlegroups.com
Those records are a representation of the BSON documents in the shell. The ISODate(...) field values indicate those values are of date type. To correctly query for them using Pymongo you need to use Python's date types (datetime module), which the driver will handle converting into BSON date types. Below, I've included a complete example of inserting and querying for similar documents in Python:

import pymongo
import datetime

mc = pymongo.MongoClient() # assuming server on localhost:27017
test = mc.test.test
test.drop()

doc0 = { "VERSION" : None, "CREATE_DATE" : datetime.datetime(2015, 1, 1) }
doc1 = { "VERSION" : None, "CREATE_DATE" : datetime.datetime(2015, 1, 29) }
test.insert(doc1)
test.insert(doc2)

cursor = test.find({ "CREATE_DATE" : { "$gt" : datetime.datetime(2015, 1, 15) } })
for res in cursor:
    print(res)
# 1 result
{u'VERSION': None, u'_id': ObjectId('54ca5611461a2e7f65db7530'), u'CREATE_DATE': datetime.datetime(2015, 1, 29, 0, 0)}

If you go into the mongo shell and use db.test.find() to see the two document in the test.test namespace, you will get

> db.test.find()

{ "_id" : ObjectId("54ca560d461a2e7f65db752f"), "VERSION" : null, "CREATE_DATE" : ISODate("2015-01-01T00:00:00Z") }
{ "_id" : ObjectId("54ca5611461a2e7f65db7530"), "VERSION" : null, "CREATE_DATE" : ISODate("2015-01-29T00:00:00Z") }

-Will

Reply all
Reply to author
Forward
0 new messages