S.D.
S.D.

Reputation: 1201

Adding a field with a value to a document returned by mongo

I'm trying to add a timestamp field to each document returned by mongo using Python. Following is the snippet I'm using to do this but I am getting an error. Can someone help achieving this?

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

Output:

{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

Error:

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

Upvotes: 1

Views: 57

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49814

stats is not a list, it is a 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
}

Set the timestamp field directly with:

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

Upvotes: 1

Related Questions