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 文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!