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?
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'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With