首页 > 解决方案 > 使用 PyMongo 用自己的值更新所有 MongoDB 字段

问题描述

我想使用字段自己的值来更新我的 MongoDB 集合的每个字段。

示例:如果我有这个文档:"string": "foo",可能的更新会这样做:"string": $string.lower()。在这里,$string将是"foo",但我不知道如何使用 PyMongo 做到这一点。

我试过这个:

user_collection.update_many({}, { "$set": { "word": my_func("$word")}})

它将所有内容替换为"$word".

我已经能够成功地迭代每个文档,但这需要太长时间。

标签: pythonmongodbpymongo

解决方案


据我所知,您无法使用 python 函数在一个语句中查找和更新。您可以使用 mongo 查询语言:

user_collection.update_many({}, { "$set": {"name": { "$concat": ["$name", "_2"]}}})

或使用 pymongo 的单独功能:

for obj in user_collection.find({some query here}):
    user_collection.update({"_id": obj['_id']}, { "$set": {"name": my_func(obj['name']) } })

推荐阅读