用pymongo在mongodb上插入$ currentDate [英] Insert the $currentDate on mongodb with pymongo

查看:335
本文介绍了用pymongo在mongodb上插入$ currentDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试服务器mongodb的准确性. 我正在尝试插入数据序列,花点时间将其发送到数据库以了解何时插入.我正在尝试:

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

但是mongodb的变量(使用$)在python中无法识别.如何进行此集成?

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

obs:IP_REMOTE =我在远程服务器上的有效IP

然后尝试了以下操作,但只插入了一条记录.

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

推荐答案

MongoDB中的运算符在数据结构中以字符串表示.这些也是更新运算符",因此 $currentDate > 用于

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.

这样,这样就可以从服务器中插入一个带有"$ currentDate"的新记录:

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)

当然,您的收藏中没有任何东西.否则,当您要插入"/更新"时,请确保.update()语句的查询"部分与文档不匹配.

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.

MongoDB手册页中的所有文档选项均采用与MongoDB shell相关的JSON表示法,但是与许多动态类型的语言(如python,ruby和Perl)的表示法并没有什么不同.

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.

这篇关于用pymongo在mongodb上插入$ currentDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆