python - pymongo 按日期时间查询

标签 python python-2.7 pymongo

我遇到一个问题,让我头疼了将近一天。

Python 脚本是:

# 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')

问题是我上面的代码有什么问题? 或者如何使用 pymongo 脚本从 mongoDB 查询两个日期之间的数据?

最佳答案

这里有两个问题,您尝试在Database对象上调用find,还需要使用datetime.datetime进行查询> $gte$lt 对象在 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()
    ...

我还没有测试过它,但它应该可以按预期工作,希望这会有所帮助。

关于python - pymongo 按日期时间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098219/

相关文章:

python-2.7 - 在创建带有借位= True的Theano共享变量时内存不足

python - 使用allowDiskUse时语法无效:True through PyMongo

python - 使用列表随机向 channel 发送消息

jquery - 使用 Selenium WebDriver Python 上传带有隐藏输入的文件

python - 没有文字的 JSON 字符串解析器

python 打印与 __str__?

python - Pymongoaggregate() 对数组字段进行排序

python - PyMongo 类型错误

python - 如何使用 Telethon 获取转发消息的 channel /聊天/用户名?

python - 比较python中嵌套列表中列表的第一个元素