I want to insert a dict into a document as the value for a field (say v
) if this document does not exist;
db.table.update_one({'k': some_unique_key},
{'$set': {'v': {name: 'some_name'},
upsert=True)
Also if the document exists, I want to update the document by updating the dict of the same field ( v
), ie adding one name: value
pair to v
, I am wondering how to do that.
eg the original document is like,
{'k': some_key, 'v': {'name_a': 'name_a_val'}}
adding one more key:value pair name_b:name_b_val
to v
is like
{'k': some_key, 'v': {'name_a': 'name_a_val', 'name_b': 'name_b_val'}}
UPDATE
this is the solution I came up with
if not db.table.find_one({'k': some_unique_key}):
db.table.insert_one({'k': some_unique_key, 'v': {'name_a': 'name_a_val'})
else:
v_val_dict = db.table.find_one({'k': some_unique_key})['v']
vat_cache.update_one({'k': some_unique_key},
{'$set': {'v': v_val_dict.update({'name_b': 'name_b_val'})}})
I am wondering if there is a better way to do this.
you have to use the dot notation . This will update the nested field named name_a
or will create it inside v
if it doesn't exist.
coll.update_one({'k': 'some_key'},
{'$set': { 'v.name_a': 'name_a_val'}}, upsert=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.