使用pymongo按mongodb中的时间范围查询

时间:2014-10-14 03:51:38

标签: python mongodb pymongo

需要对数据库mongodb执行查询,从而按时间范围生成一组结果。我正在使用pymongo。我的查询如下:

query = {"$and": [
                     {"id_node": id_node}
                     {"port": port},
                     {"datetime": {"$gte": self.hourBegin}}
                     {"datetime": {"$lte": self.now}}
                     ]}
listResults = db.mycollection.find (query)

我也尝试过这种方式:

query = {"id_node": int(id_node)
                     "port": port,
                     "datetime": {"$gte": self.hourBegin, "$lte": self.now}}
listResults = db.mycollection.find (query)

但结果总是空的。直接在mongodb中测试但结果为空。我确信数据存在于数据库中,其中包含我正在研究的时间范围。

可能结果列表:

{ "_id" : ObjectId("543618c6e7b9914c35266128"), "lab" : "2", "port" : "A1", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:04Z"), "valor" : "22.00", "sensor" : "2" }
{ "_id" : ObjectId("543618c6e7b9914c35266129"), "lab" : "2", "port" : "A0", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:04Z"), "valor" : "0", "sensor" : "1" }
{ "_id" : ObjectId("543618c6e7b9914c3526612c"), "lab" : "2", "port" : "A1", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:06Z"), "valor" : "22.00", "sensor" : "2" }
{ "_id" : ObjectId("543618c6e7b9914c3526612d"), "lab" : "2", "port" : "A0", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:06Z"), "valor" : "0", "sensor" : "1" }
{ "_id" : ObjectId("543618c7e7b9914c35266130"), "lab" : "2", "port" : "A1", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:08Z"), "valor" : "22.00", "sensor" : "2" }
{ "_id" : ObjectId("543618c7e7b9914c35266131"), "lab" : "2", "port" : "A0", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:08Z"), "valor" : "0", "sensor" : "1" }
{ "_id" : ObjectId("543618c7e7b9914c35266134"), "lab" : "2", "port" : "A1", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:10Z"), "valor" : "22.00", "sensor" : "2" }
{ "_id" : ObjectId("543618c7e7b9914c35266135"), "lab" : "2", "port" : "A0", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:10Z"), "valor" : "0", "sensor" : "1" }
{ "_id" : ObjectId("543618c7e7b9914c35266138"), "lab" : "2", "port" : "A1", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:12Z"), "valor" : "22.00", "sensor" : "2" }
{ "_id" : ObjectId("543618c7e7b9914c35266139"), "lab" : "2", "port" : "A0", "id_node" : 1, "datetime" : ISODate("2014-09-26T18:28:12Z"), "valor" : "0", "sensor" : "1" }

1 个答案:

答案 0 :(得分:4)

我访问http://www.querymongo.com/,然后创建一个查询,好像它在MySQL中,然后必须返回一个mongodb查询。像这样:

#MySQL Query
SELECT * FROM inoshare WHERE id_nome = 1 AND port = 1 AND datetime > 'hourBegin' AND datetime <= 'NOW()';

回归:

db.inoshare.find({
"id_nome": 1,
"port": 1,
"datetime": {
    "$gt": "hourBegin",
    "$lte": "NOW()"
}
});

然后将'hourBegin'和'NOW()'替换为变量。 谢谢所有人。