Reputation: 305
Hi I am trying to update values in my database. I have the following data:
{'_id': 123,
'keys':
{'values':
{'value1': 1,
'value2: 2,
}
{
I am trying to update the values with the following query:
new_values = {'value3': 3,
'value4': 4}
col.update_one({'_id': 123},{"$set": {"keys": new_values}})
Expected result:
{'_id': 123,
'keys':
{'values':
{'value1': 1,
'value2': 2,
'value3': 3,
'value4': 4,
}
{
Actual result:
{'_id': 123,
'keys':
{'values':
{'value3': 3,
'value4': 4,
}
{
What am I missing, should I update it field for field in a loop over the new_values
?
Upvotes: 0
Views: 35
Reputation: 3349
You are trying to replace the values in key values
instead of add new sub-keys.
There are two solutions to your problem.
Solution - 1
Specify the absolute key naming for each sub-keys in the update command
col.update_one({'_id': 123},{"$set": {"keys.values.value3": 3, "keys.values.value4": 4}})
Solution - 2
Get the existing value by find_one
command and perform update_one
operation joining the two dictionaries.
new_values = {'value3': 3,
'value4': 4}
temp = col.find_one({'_id': 123}, {"keys": 1})
dict_to_insert = {**new_values, **temp["keys"]["values"]}
col.update_one({'_id': 123},{"$set": {"keys.values": dict_to_insert}})
I would suggest you go with solution 2, although it performs an additional read operation to get it done.
Upvotes: 1