使用pymongo在一个statemet中更新查找结果

时间:2018-07-03 11:14:39

标签: python pymongo

我有这样的功能:

def max_number(list_):
    dict_ = {
     "a": 1,
     "b": 2,
     "c": 3,
     "d": 4
    }
    list_ = [dict_[i] for i in list_]
    return max(list_)

db.test.find()返回:

{"name": "name1", "level": ["a", "d"]}
{"name": "name2", "level": ["c"]}
{"name": "name3", "level": ["a", "c"]}

现在,我想使用功能max_number在每条记录中获得最大水平,更新后的结果应类似于:

{"name": "name1", "level": ["a", "d"], "max": 4}
{"name": "name2", "level": ["c"], "max": 3}
{"name": "name3", "level": ["a", "c"], "max": 3}

我知道我可以使用find(),然后使用for循环逐个更新它。 但是我不知道是否有一种方法可以帮助我在一条语句中完成此任务,就好像我有一个大的collection一样,使用for循环来完成此任务可能会很慢。

该语句可能类似于:

db.test.update_many({}, {"$set": {"max": max_number(result.level)}})

1 个答案:

答案 0 :(得分:1)

根据您在问题中提到的信息。下面的解决方案可以完成这项工作。

cursor_list=list(db.test.find())
# cursor_list=[{"name": "name1", "level": ["a", "d"]},{"name": "name2", "level": ["c"]},{"name": "name3", "level": ["a", "c"]}]
value_l=[d["level"] for d in cursor_list]
# value_l=[['a', 'd'], ['c'], ['a', 'c']]

name_l=[d["name"] for d in cursor_list]

dict_ = {
     "a": 1,
     "b": 2,
     "c": 3,
     "d": 4
    }

def replace_matched_items(word_list, dictionary):
"""maps the value in sublist to the dict values"""

    new_list = [[dictionary.get(item, item) for item in lst] for lst in word_list]
    return new_list

list_ = replace_matched_items(value_l, dict_)
# list_=[[1, 4], [3], [1, 3]]
max_value=[max(l) for l in list_]
# max_value=[4, 3, 3]
# it updates to the field "max" wrt to the "name" field which I supposed is unique
for i in range(len(value_l)):
    db.test.update({"name": name_l[i]}, {"$set": {"max": max_value[i]}})