简体   繁体   中英

How to make a query date in mongodb using pymongo?

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) 

@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

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM