2

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()
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
carlaodev
  • 621
  • 2
  • 8
  • 18

3 Answers3

4

You should pass the python code to mongo like this,

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

Your code:

pacote = {'contador':contador, 'datahora':datetime.now()}
dhana
  • 6,487
  • 4
  • 40
  • 63
  • sorry, forgot to put in the code that the server is remote. with the 'now()' I get the time from the local machine. i need the instant that is inserted into the database. – carlaodev Nov 08 '14 at 05:30
  • I think in this case use `pytz` module related remote server time zone. – dhana Nov 08 '14 at 05:35
  • 2
    @dhana This was more about using MongoDB than python code. The [**`$currentDate`**](http://docs.mongodb.org/manual/reference/operator/update/currentDate/) operator is a special one that sets the date based on what the "server time" actually is. So without passing a date determined by code through to the server. That is what the OP was asking. Anything else comes from the "client", even though you "should" have synchronized time in good practice. – Neil Lunn Nov 08 '14 at 06:18
4

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • I did as instructed, but the remote database is only inserted one record. Need it to insert the same amount, so I can compare the timestamp. Only then will I know how long it takes for the bank to insert a tuple @Neil – carlaodev Nov 08 '14 at 17:49
  • @touchmx You can "update" multiple records with the "multi" option as documented on the `.update()` method. Perhaps you are misunderstanding that `$currentDate` does though. The updated timestamp will be reflective of the actual time that record was updated. If you supplied a set date from the client, then **all** updated records would share the same timestamp. With `$currentDate` then they will likely not. – Neil Lunn Nov 09 '14 at 01:06
0

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.

carlaodev
  • 621
  • 2
  • 8
  • 18