如何使用pymongo使MongoDB中查询日期?如何使用pymongo使MongoDB中查询日期?

2019-05-12 03:20发布

我想在MongoDB中执行查询的日期,但结果总是空的。 我的查询如下:

//in the begin code
def __init__(self):
    self.now = datetime.now()
    self.db = conexaoMongo()
    self.horaInicio = self.now - timedelta(minutes=1)

def resultadoConsulta(self, modo, porta, id_node):
    #print "Porta e No ", porta, id_node
    resultadoMongo = []
    mediaFinal = False      
    try:

        json = {'id_no': int(id_node), 'datahora': {'$gte': self.horaInicio, '$lt': self.now}, 'porta': porta}

        print "COnsulta a ser realizada: ", json
        resultadoMongo = self.db.queryMongoOne(json) 

//变量resultaMongo空车返回。

OBS:我也尝试不使用.isoformat()当我把在MongoDB中直接,只有当我添加ISODate返回结果。 因此,不返回的结果:

db.inoshare.find( {'id_no': 1, 'datahora': {'$lte': '2014-09-24T07:52:04.945306', '$gte': '2014-09-24T07:51:04.958496'}, 'porta': 'A0'})

更何况,如果你编辑的回报:

db.inoshare.find( {'id_no': 1, 'datahora': {'$lte': ISODate('2014-09-24T07:52:04.945306'), '$gte': ISODate('2014-09-24T07:51:04.958496')}, 'porta': 'A0'})

这是记录在数据库中的序列:

    { "_id" : ObjectId("5435be9ce7b9916e02ed2cb5"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:05Z"), "valor" : "917", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cb9"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:07Z"), "valor" : "932", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cbd"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:09Z"), "valor" : "189", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cc1"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:11Z"), "valor" : "853", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cc5"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:13Z"), "valor" : "202", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cc9"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:15Z"), "valor" : "398", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2ccd"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:17Z"), "valor" : "947", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cd1"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:19Z"), "valor" : "57", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cd5"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:21Z"), "valor" : "395", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cd9"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:23Z"), "valor" : "941", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2cdd"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:25Z"), "valor" : "208", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2ce1"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:27Z"), "valor" : "186", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2ce5"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:29Z"), "valor" : "848", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2ce9"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:31Z"), "valor" : "571", "sensor" : "1" }
    { "_id" : ObjectId("5435be9ce7b9916e02ed2ced"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:33Z"), "valor" : "351", "sensor" : "1" }
    { "_id" : ObjectId("5435be9de7b9916e02ed2cf1"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:35Z"), "valor" : "558", "sensor" : "1" }
    { "_id" : ObjectId("5435be9de7b9916e02ed2cf5"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:37Z"), "valor" : "449", "sensor" : "1" }
    { "_id" : ObjectId("5435be9de7b9916e02ed2cf9"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:39Z"), "valor" : "768", "sensor" : "1" }
    { "_id" : ObjectId("5435be9de7b9916e02ed2cfd"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:41Z"), "valor" : "542", "sensor" : "1" }
    { "_id" : ObjectId("5435be9de7b9916e02ed2d01"), "lab" : "2", "porta" : "A0", "id_no" : 1, "datahora" : ISODate("2014-09-24T07:51:43Z"), "valor" : "763", "sensor" : "1" }

如果我打印蟒JSON变量,我看到类似这样的:

{'id_no': 1, 'datahora': {'$gte': datetime.datetime(2014, 9, 24, 8, 21, 38, 527653), '$lt': datetime.datetime(2014, 9, 24, 8, 22, 36, 677022)}, 'porta': 'A1'}

我Mongndb类连接:

#!/usr/bin/python
from pymongo import MongoClient

class conexaoMongo:

    def __init__(self):
        self.conditions = []        
        self.client = MongoClient("127.0.0.1", 27017, safe=True)
        self.db = self.client['inoshare']
        self.ino = self.db.inoshare     


    def queryMongo(self, param1, param2=None, param3=None): 

        try:
            if param2 != None:
                results = self.ino.find(param1, param2)
            elif param3 != None:
                results = self.ino.find(param1, param2, param3)
            else:               
                results = self.ino.find(param1)

            #print "Total de registros ", results.count()

            for post in results:
                #print post
                self.conditions.append(post)

            return self.conditions

        except:
            print "Erro ao executar a query"

Answer 1:

@Joni是正确的,你需要使用datetime

from datetime import datetime
from pymongo import Connection

# i have updated and included the complete code 
client = Connection('localhost', 27017)
db = client['database'] # your database name
inoshare = db['inoshare']


# convert your date string to datetime object
start = datetime(2014, 9, 24, 7, 51, 04)
end = datetime(2014, 9, 24, 7, 52, 04)

inoshare.find( {'id_no': 1, 'datahora': {'$lt': end, '$gte': start}, 'porta': 'A0'})
<pymongo.cursor.Cursor at 0x7f9aafd64a90>

inoshare.find_one( {'id_no': 1, 'datahora': {'$lt': end, '$gte': start}, 'porta': 'A0'})

{u'_id': ObjectId('5435be9ce7b9916e02ed2cb5'),
 u'datahora': datetime.datetime(2014, 9, 24, 7, 51, 5),
 u'id_no': 1.0,
 u'lab': u'2',
 u'porta': u'A0',
 u'sensor': u'1',
 u'valor': u'917'}

显然我可以成功地返回结果。 也许你的数据被破坏,或者你应该张贴所有的代码我们审查



Answer 2:

在ISODate属性查询条件应该使用Python的datetime.datetime对象。

也就是说,不要格式化你的日期与使用isoformat函数字符串,利用它们,因为它们。



文章来源: How to make a query date in mongodb using pymongo?