33

I'm trying to perform a query date in mongodb, but the result is always empty. My query is as follows:

//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) 

//variable resultaMongo return empty.

Obs: I also tried without using .isoformat() When I put in mongodb directly, only return results if I add ISODate. So does not return results:

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

More so if you edit returns:

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

This is a sequence of records in the database:

    { "_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" }

if i print the json variable of python, i see something like:

{'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'}

My Mongndb Class connection is:

#!/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"
Community
  • 1
  • 1
carlaodev
  • 621
  • 2
  • 8
  • 18
  • OK, much clearly this time. first thing, you don't need to repeat `results=results`, streamline the code and just test with `test = conexaoMongo();results = test.queryMongo({..., {'$gte':datetime(...), '$lt':datetime(...)}})` – Anzel Oct 14 '14 at 18:46
  • tested this now, but it did not work. – carlaodev Oct 14 '14 at 18:55
  • and your `json` dictionary is wrong, you cannot access `self` outside `__init__`, you may either put `self.json = {...}` and pass `self.json` as params. – Anzel Oct 14 '14 at 18:56
  • I printed the contents of the json variable is in the post. – carlaodev Oct 14 '14 at 18:58
  • I can only help this far. with our answers (and code), I hope you can correct the mistakes in your code. It is quite obvious the params are not passed correctly. With some changes you should be able to get the `results` I have shown you. Good luck! – Anzel Oct 14 '14 at 18:58
  • Thank's for all @Anzel – carlaodev Oct 14 '14 at 19:04

4 Answers4

69

@Joni is correct, you need to use 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'}

clearly I can successfully return results. Perhaps your data is corrupt, or you should post all your code for us to review

Anzel
  • 19,825
  • 5
  • 51
  • 52
  • A example for start: datetime(2014, 9, 24, 8, 32, 37, 745578); A examplor for end: datetime(2014, 9, 24, 8, 33, 37, 731647); No results. – carlaodev Oct 14 '14 at 17:43
  • ah I see, you store the date with `ISODate` – Anzel Oct 14 '14 at 17:45
  • you need a conversion between those, since normally on mongo `date` is store as `Date` object – Anzel Oct 14 '14 at 17:46
  • i've edited to convert the datetime to isoformat, can you test and see if this works? – Anzel Oct 14 '14 at 17:50
  • you mean `datetime.datetime(2014,9,24,7,51,04).isoformat()` not working? – Anzel Oct 14 '14 at 17:55
  • Look: self.now = datetime.now() and self.horaInicio = self.now - timdelta(minutes=1). It is not the same thing as you suggested? – carlaodev Oct 14 '14 at 18:20
  • where does this `self.now` came from? Can you clearly explain what you want to achieve and what code you exactly use to return the `query`? I have created a db with a few of your db objects and I can clearly query the results as expected – Anzel Oct 14 '14 at 18:23
  • are you doing your query under **python** shell, or **mongo** shell? – Anzel Oct 14 '14 at 18:24
  • if you are using **python** with `pymongo` modules, you need to use `datetime`, if you want to test your query in **mongo shell**, you need to use **javaScript** which is *ISODate* – Anzel Oct 14 '14 at 18:27
  • I read your edit, you still haven't shown the code where you actually make your query. Please see my updated answer. – Anzel Oct 14 '14 at 18:33
5

Query conditions on ISODate attributes should use Python's datetime.datetime objects.

That is, don't format your dates as strings using the isoformat function, use them as they are.

Joni
  • 108,737
  • 14
  • 143
  • 193
0

The problem is the '04' at the end of

start = datetime(2014, 9, 24, 7, 51, 04)

"SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers"

If you write this way, the problem is solved:

start = datetime.datetime(2014, 9, 24, 7, 51, 4).
-1

If start = datetime(2014, 9, 24, 7, 51, 04) is throwing error,

Try using
start = datetime.datetime(2014, 9, 24, 7, 51, 04).

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Meet Patel
  • 89
  • 1
  • 3