【问题标题】:How to update a list of dicts in pymongo?如何更新 pymongo 中的字典列表?
【发布时间】:2021-10-23 12:47:39
【问题描述】:

我收藏了一些类似的记录:

{ 
    '_id': 1,
    'test_field': [{'key1': 'value1'}, {'key2': 'value2'}]
}

test_field 是一个字典列表。如果任何键不存在,我需要在该列表中推送新的字典,如果存在,我需要更新该键的值。

示例:

  1. {'key1': 'test_value'}'test_field': [{'key1': 'test_value'}, {'key2': 'value2'}]
  2. {'test_key': 'test_value2'}'test_field': [{'key1': 'value1'}, {'key2': 'value2'}, {'test_key': 'test_value_2'}]

请帮忙

【问题讨论】:

  • 可以使用更新操作-$push。您可以在更新的 filter 中检查列表元素是否存在。或者,您可以只做一个$addToSet,这将仅在 t 不存在时添加列表元素。
  • 我知道。但是只有当键不存在时,我才需要在列表中推送新的字典。如果密钥存在,我需要更新它的值。
  • 然后你就可以使用聚合管道更新(这是MongoDB v4.2或更高版本的一个特性)。

标签: python mongodb list dictionary pymongo


【解决方案1】:

如果您需要 python 中的函数来执行此操作,这可能对您有用。

def modify_test_field(my_dict, test_field, new_key, new_val):
    my_dict[test_field] = [obj for obj in my_dict[test_field] if new_key not in obj]
    my_dict[test_field].append({new_key: new_val})

并称它为modify_test_field(orig_dict, 'test_field', new_key, new_val)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2017-02-01
    • 2022-08-12
    • 2019-02-18
    相关资源
    最近更新 更多