Victor
Victor

Reputation: 77

pymongo query by datetime

I got one problem which made me headache for almost one day.

The python scripts are:

# coding:utf-8
import pymongo
import datetime, time

def query_data(IP,datefrom,dateto):
    conn = pymongo.MongoClient(IP)
    db = conn.mymongo

    startdate = time.mktime(time.strptime(datefrom,'%Y-%m-%d'))
    enddate = time.mktime(time.strptime(dateto,'%Y-%m-%d'))

    # all above are correct definitely.
    #
    # but I got no result from this line below.
    cursor = db.find({'username':'test','created':{'$gte':startdate,'$lt':enddate}})
    print cursor.count()
    # with above code, I got 0 returned though I can see it is nonzero in database.
    # 
    # If I use this below with single datetime, I can see result. But it is not my intention.
    # cursor = db.find({'username':'test','created':datefrom})
    # print cursor.count()

    tempData = []
    for doc in cursor:
        print doc['twitter']
        tempData.append(doc['twitter'])

    print len(tempData)
    return tempData

result = query_data('192.168.100.20','2014-4-1','2014-5-1')

The question is what was wrong with my code above? Or how can I query data from mongoDB between two dates, with pymongo script?

Upvotes: 1

Views: 11565

Answers (1)

Anzel
Anzel

Reputation: 20553

There are 2 problems here, you are trying to call find on a Database object, also you need to query with the datetime.datetime object for $gte and $lt to work properly in mongodb.

def query_data(IP,datefrom,dateto):
    conn = pymongo.MongoClient(IP)
    db = conn.mymongo

    # time.mktime will only return a float point number
    # what you really need are the datetime.datetime objects
    startdate = datetime.datetime.strptime(datefrom,'%Y-%m-%d')
    enddate = datetime.datetime.strptime(dateto,'%Y-%m-%d')

    # you need to call find method on collection, not database object
    cursor = db['your_collection'].find({'username':'test','created':{'$gte':startdate,'$lt':enddate}})
    print cursor.count()
    ...

I haven't tested it but it should then work as expected, and hope this helps.

Upvotes: 3

Related Questions