Insert the $currentDate on mongodb with pymongo
Question: 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()
    


Answer: Operator expressions in MongoDB are represented in the data structure as a
string. These are also "update operators", so
[**`$currentDate`**](http://docs.mongodb.org/manual/reference/operator/update/currentDate/)
is meant to be used in the "update object" portion of an
[`.update()`](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.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.

