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
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
