python - 使用 PyMongo 用自己的值更新所有 MongoDB 字段
问题描述
我想使用字段自己的值来更新我的 MongoDB 集合的每个字段。
示例:如果我有这个文档:"string": "foo"
,可能的更新会这样做:"string": $string.lower()
。在这里,$string
将是"foo"
,但我不知道如何使用 PyMongo 做到这一点。
我试过这个:
user_collection.update_many({}, { "$set": { "word": my_func("$word")}})
它将所有内容替换为"$word"
.
我已经能够成功地迭代每个文档,但这需要太长时间。
解决方案
据我所知,您无法使用 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']) } })
推荐阅读
- android - 设备重新启动后,警报管理器在给定时间之前启动
- apache - .htaccess php 中的重定向规则
- c# - 例如,是否可以在手机上打开游戏,或者在我的应用程序中进入图库?
- assembly - 无法弄清楚为什么我在 YouTube 上找到的 MIPS 汇编语言代码中遇到错误
- ios - 如何在IOS上通过硬件播放解码的音频数据?
- javascript - 如何在 JavaScript 中获取创建的音频元素的文件大小?
- node.js - 使用 Dgraph:在保存之前将操作暴露给前端并处理突变
- reactjs - Reactjs 中的 Unicode 表情符号渲染
- pandas - plot_recursive_coefficient statsmodels 创建子图
- ios - 如何改进 iOS Safari 对 PDF 作为 blob 链接的处理?