Append item to MongoDB document array in PyMongo without re-insertion(无需重新插入即可将项目附加到 PyMongo 中的 MongoDB 文档数组)
问题描述
我使用 MongoDB 作为 Python Web 应用程序 (PyMongo + Bottle) 的后端数据库.用户可以上传文件,并可以在上传过程中选择标记"这些文件.标签作为列表存储在文档中,如下所示:
I am using MongoDB as the back-end database for Python web application (PyMongo + Bottle). Users can upload files and optionally 'tag' these files during upload. The tags are stored as a list within the document, per below:
{
"_id" : ObjectId("561c199e038e42b10956e3fc"),
"tags" : [ "tag1", "tag2", "tag3" ],
"ref" : "4780"
}
我正在尝试允许用户将新标签附加到任何文档.我想出了这样的事情:
I am trying to allow users to append new tags to any document. I came up with something like this:
def update_tags(ref, new_tag)
# fetch desired document by ref key as dict
document = dict(coll.find_one({'ref': ref}))
# append new tag
document['tags'].append(new_tag)
# re-insert the document back into mongo
coll.update(document)
(仅供参考;ref 键始终是唯一的.这也很容易是 _id.)似乎应该有一种方法可以直接更新标签"值,而无需拉回整个文档并重新插入.我在这里遗漏了什么吗?
(fyi; ref key is always unique. this could easily be _id as well.)
It seems like there should be a way to just update the 'tags' value directly without pulling back the entire document and re-inserting. Am I missing something here?
非常感谢任何想法:)
推荐答案
您不需要先使用检索文档,只需使用带有 .update 方法://docs.mongodb.org/manual/reference/operator/update/push/" rel="noreferrer">$push 操作符.
You don't need to use to retrieve the document first just use the .update method with the $push operator.
def update_tags(ref, new_tag):
coll.update({'ref': ref}, {'$push': {'tags': new_tag}})
由于更新已弃用,您应该使用 find_one_and_update 或 update_one 方法,如果您使用的是 pymongo 2.9 或更新版本
Since update is deprecated you should use the find_one_and_update or the update_one method if you are using pymongo 2.9 or newer
这篇关于无需重新插入即可将项目附加到 PyMongo 中的 MongoDB 文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无需重新插入即可将项目附加到 PyMongo 中的 Mon
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
