Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo, mongodb add a new key to an existing dictionary

How to update a dicitonary element of a record to add a new key if not exist or update the corresponding value of the key, if it exists. For example:

record = {'_id':1,
            'value': {'key1' : '200'}}

I wish to update the 'value' by adding a new key-value pair. e.g. value={'key2':'300'}. So my desired updated record would be:

    record = {'_id':1,
                'value': {'key1' : '200',
                          'key2' : '300'}}

I've tried:

    value={'key2':'300'}
    mongo.db['mydb'].update(
            {'_id': 1},
            {'$set': {'value': value}})

But it overwrites the 'value' and does not add the new key to it:

record = {'_id':1,
            'value': {'key2' : '300'}}

How can I achieve that?

like image 783
CentAu Avatar asked Jul 21 '15 13:07

CentAu


1 Answers

You need to use the "dot notation"

In [20]: col.find_one()
Out[20]: {'_id': 1, 'value': {'key1': '200'}}

In [21]: col.update({'_id': 1}, {'$set': {'value.key2': 300}})
Out[21]: {'n': 1, 'nModified': 1, 'ok': 1, 'updatedExisting': True}

In [22]: col.find_one()
Out[22]: {'_id': 1, 'value': {'key1': '200', 'key2': 300}}

EDIT

If your key is in variable all you need is concatenation:

In [37]: key2 = 'new_key'

In [38]: col.update({'_id': 1}, {'$set': {'value.' + key2: 'blah'}})
Out[38]: {'n': 1, 'nModified': 1, 'ok': 1, 'updatedExisting': True}

In [39]: col.find_one()
Out[39]: {'_id': 1, 'value': {'key1': '200', 'new_key': 'blah'}}
like image 59
styvane Avatar answered Nov 10 '22 08:11

styvane