将具有值的字段添加到mongo返回的文档中

时间:2017-04-20 00:12:06

标签: python mongodb pymongo

我正在尝试使用Python为timestamp返回的每个文档添加mongo字段。以下是我用来做这个的片段,但是我收到了一个错误。有人可以帮助实现这个目标吗?

def get_dbstats(self, client):
    dbs = client.database_names()
    for db in dbs:
        stats = client[db].command('dbstats')
        print stats
        print (datetime.datetime.now())
        stats[0]['created_time'] = datetime.datetime.now()

输出:

{u'storageSize': 90112.0, u'ok': 1.0, u'avgObjSize': 293.0, u'db': u'admin', u'indexes': 5, u'objects': 13, u'collections': 3, u'numExtents': 0, u'dataSize': 3809.0, u'indexSize': 163840.0}
2017-04-19 17:05:26.711000

错误:

Traceback (most recent call last):
  File "H:/Python01/script01.py", line 28, in <module>
    obj.get_dbstats(client)
  File "H:/Python01/script01.py", line 22, in get_dbstats
    stats[0]['timestamp'] = datetime.datetime.now()
KeyError: 0

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

stats不是list,而是dict

stats = {   
    u'storageSize': 90112.0, 
    u'ok': 1.0, 
    u'avgObjSize': 293.0, 
    u'db': u'admin', 
    u'indexes': 5, 
    u'objects': 13, 
    u'collections': 3, 
    u'numExtents': 0, 
    u'dataSize': 3809.0, 
    u'indexSize': 163840.0
}

直接使用以下方式设置时间戳字段:

stats['timestamp'] = datetime.datetime.now()