【问题标题】:Update all MongoDB fields with their own values with PyMongo使用 PyMongo 使用自己的值更新所有 MongoDB 字段
【发布时间】:2020-01-27 20:52:35
【问题描述】:

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

示例:如果我有此文档:"string": "foo",则可能的更新将执行此操作:"string": $string.lower()。在这里,$string 将是 "foo",但我不知道如何使用 PyMongo 执行此操作。

我试过这个:

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

"$word" 替换所有内容。

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

【问题讨论】:

  • 据我了解,您正在阅读同一个文档并使用每个键的不同值更新同一个文档。可能是 replace_one 方法会更适合这个。如果您添加更多详细信息,例如如何获取文档和更新功能,将有助于提出更好的建议。
  • 我想为我的集合中的每个文档更新一个字段。昨天我不得不传递一个urllib.parse 函数来解码每个文档的某个字段。现在我想要使用.strip() 方法来做同样的事情。在这种情况下,使用 MongoDB 的内置 $trim 可能是可行的。

标签: python mongodb pymongo


【解决方案1】:

据我所知,您无法使用 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']) } })

【讨论】:

    猜你喜欢
    • 2022-04-13
    • 2021-05-21
    • 2020-06-12
    • 1970-01-01
    • 2020-12-24
    • 2013-03-07
    • 2017-04-08
    • 2011-04-27
    相关资源
    最近更新 更多