gpt4 book ai didi

python - pymongo,mongodb 向现有字典添加新键

转载 作者:可可西里 更新时间:2023-11-01 10:28:03 26 4
gpt4 key购买 nike

如何更新记录的字典元素以添加新键(如果不存在)或更新键的相应值(如果存在)。例如:

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

我希望通过添加新的键值对来更新 'value'。例如value={'key2':'300'}。所以我想要的更新记录是:

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

我试过:

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

但它会覆盖“值”并且不会向其添加新键:

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

我怎样才能做到这一点?

最佳答案

您需要使用 "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}}

编辑

如果您的 key 在变量中,您只需要串联:

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'}}

关于python - pymongo,mongodb 向现有字典添加新键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31540403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com