$ gte

时间:2018-07-03 11:53:51

标签: python mongodb pymongo

我正在使用Pymongo。我已经成功连接到我的MongoDB。集合名称为test_collection。在文档中,有一个名为request_time的密钥。我正在尝试获取request_time特定范围内的文档。

在mongodb shell中,此命令有效,

db.getCollection('test_collection').find({ request_time: { $gte: new Date('2018-06-22'), $lt: new Date('2018-06-26') }});

但是,当我使用pymongo时。它不接受$并给出语法错误。

collection = db['test_collection']

cursor = collection.find({request_time: { $gte: new Date('2018-06-22'), $lt: new Date('2018-06-26') }})

3 个答案:

答案 0 :(得分:1)

您在mongo shell中使用Javascript编写命令,请勿将其复制粘贴到python中。 Python不是Javascript。

Python既没有new也没有内置Date类型。

pymongo.collection.Collection类的

find方法要求字典带有字符串键,将键放在引号中。

如果mongo集合中文档中的各个字段为ISODate,请使用datetime.datetime

import datetime 
cursor = collection.find({"request_time": { 
                          "$gte": datetime.datetime(2018, 6, 22), 
                          "$lt": datetime.datetime(2018, 6, 26) }
                         })

答案 1 :(得分:-2)

尝试在每种情况下放置Brasket

({{{$ gte:new Date('2018-06-22')},{$ lt:new Date('2018-06-26')}})

答案 2 :(得分:-2)

在代码中使用'$ gt''$ lt'

cursor = collection.find({request_time: { '$gte': new Date('2018-06-22'), '$lt': new Date('2018-06-26') }})
相关问题