Insert the $currentDate on mongodb with pymongo

情到浓时终转凉″ 提交于 2019-12-24 10:30:56

问题


I need test the accuracy of a server mongodb. I am trying to insert a sequence of data, take the moment and it was sent to the database to know when it was inserted. I'm trying this:

#!/usr/bin/python
from pymongo import Connection
from datetime import date, timedelta, datetime

class FilterData:

@classmethod
def setData(self, serialData):
    try:
        con = Connection('IP_REMOTE', 27017, safe=True)
        db = con['resposta']            
        inoshare = db.resposta
        inoshare.insert(serialData)            
        con.close()

    except  Exception as e:
        print "Erro no filter data: ", e.message, e.args

obj = FilterData()
inicio = datetime.now()
termino = inicio + timedelta(seconds=10)
contador = 1

while inicio <= termino:
    print contador, inicio.strftime('%d-%m-%Y %H:%M:%S')
    pacote = {'contador':contador, 'datahora':$currentDate()}
    obj.setData(pacote)
    contador += 1

But the variables of mongodb (using $) are not recognized in python. How to proceed to accomplish this integration?

Obs: IP_REMOTE = my valid IP on REMOTE server

then tried the following, but only inserts a single record.

#!/usr/bin/python
from pymongo import Connection
from datetime import date, timedelta, datetime
import time

class FilterData:

    def __init__(self):
        self.con = Connection('54.68.148.224', 27017, safe=True)
        self.db = self.con['resposta']            
        self.inoshare = self.db.resposta

    def setData(self, serialData):
        try:

            self.inoshare.update({}, serialData, upsert=True)            

        except  Exception as e:
            print "Erro no filter data: ", e.message, e.args

    def desconect(self):
        self.con.close()

obj = FilterData()
inicio = datetime.now()
termino = inicio + timedelta(seconds=30)

while inicio <= termino:
    print inicio.strftime('%d-%m-%Y %H:%M:%S')
    pacote = {'$currentDate': {'datahora': { '$type': 'date' }}}
    obj.setData(pacote)
    inicio = datetime.now()
    time.sleep(1)

obj.desconect()

回答1:


Operator expressions in MongoDB are represented in the data structure as a string. These are also "update operators", so $currentDate is meant to be used in the "update object" portion of an .update() method.

So something like this to insert a new record with the "$currentDate" from the server:

db = con['resposta']            
inoshare = db.resposta
inoshare.update({}, { 
    '$currentDate': {
        'datahora': { '$type': 'date' }
    }
},upsert=True)

Presuming of course there is nothing in your collection. Otherwise make sure the "query" portion of the .update() statement does not match a document when you want to "insert"/"upsert" as it were.

All the documentation options in the MongoDB manual pages are as JSON notation relevant to the MongoDB shell, but however this is not that different from the notation of many dyamically typed languages such as python, ruby and Perl.

BTW. Unless you are really testing in distinct scripts, then do not make a connection and disconnect before and after every operation. Database collections should stay open for the life-cycle of your application.




回答2:


You should pass the python code to mongo like this,

>>> from datetime import datetime
>>> datetime.now()

Your code:

pacote = {'contador':contador, 'datahora':datetime.now()}



回答3:


Thanks to everyone who helped me. I understand now, first do an insert and then an update. Like this:

class FilterData:

    def __init__(self):
        self.con = Connection('IP_REMOTE', 27017, safe=True)
        self.db = self.con['resposta']            
        self.inoshare = self.db.resposta
        self.contador = 1

    def setData(self, serialData):
        try:

            self.inoshare.insert({'contador': self.contador}, serialData, upsert=True)      
            print self.contador, datetime.now().strftime('%d-%m-%Y %H:%M:%S.%f')
            self.inoshare.update({'contador': self.contador}, serialData, upsert=True)
            self.contador += 1

        except  Exception as e:
            print "Erro no filter data: ", e.message, e.args

    def desconect(self):
        self.con.close()

that way I can check the time that the query was sent and the moment she was executed on the remote server. On-site host I have the following output, for example:

1 08-11-2014 15:37:45.079000

1 08-11-2014 15:38:04.039000

2 08-11-2014 15:38:05.410000

3 08-11-2014 15:38:06.785000

4 08-11-2014 15:38:08.153000

5 08-11-2014 15:38:09.522000

6 08-11-2014 15:38:10.886000

7 08-11-2014 15:38:12.243000

8 08-11-2014 15:38:13.609000

And on the remote server I get the following output:

{"contador" : 1, "datahora" : ISODate("2014-11-08T18:38:05.323Z") }

{"contador" : 2, "datahora" : ISODate("2014-11-08T18:38:06.687Z") }

{"contador" : 3, "datahora" : ISODate("2014-11-08T18:38:08.060Z") }

{"contador" : 4, "datahora" : ISODate("2014-11-08T18:38:09.429Z") }

{"contador" : 5, "datahora" : ISODate("2014-11-08T18:38:10.796Z") }

{"contador" : 6, "datahora" : ISODate("2014-11-08T18:38:12.162Z") }

{"contador" : 7, "datahora" : ISODate("2014-11-08T18:38:13.527Z") }

{"contador" : 8, "datahora" : ISODate("2014-11-08T18:38:14.893Z") }

That way I can identify the time difference between the time of the update and the moment he really was iserido in the database. Note: The clocks are synchronized.



来源:https://stackoverflow.com/questions/26814040/insert-the-currentdate-on-mongodb-with-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!