在不重新插入的情况下将项目追加到PyMongo中的MongoDB文档数组 [英] Append item to MongoDB document array in PyMongo without re-insertion

查看:54
本文介绍了在不重新插入的情况下将项目追加到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)

(fyi; 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?

任何想法都将不胜感激:)

Any thoughts are greatly appreciated :)

推荐答案

您不需要先使用它来检索文档,只需将.update方法与

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}})

由于不建议使用更新,因此您应该使用

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆