将项追加到PyMongo中的MongoDB文档数组,而不重新插入

2024-04-24 06:56:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用MongoDB作为Python web应用程序(PyMongo+Bottle)的后端数据库。用户可以上传文件,也可以在上传过程中“标记”这些文件。标签作为列表存储在文档中,如下所示:

{
    "_id" : ObjectId("561c199e038e42b10956e3fc"),
    "tags" : [ "tag1", "tag2", "tag3" ],
    "ref" : "4780"
}

我正在尝试允许用户将新标记附加到任何文档。我想出了这样的办法:

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。) 似乎应该有一种方法可以直接更新“tags”值,而不必收回整个文档并重新插入。我是不是丢了什么东西?

任何想法都非常感激:)


Tags: 文件用户文档标记refidnewmongodb
3条回答

只需添加到@ssytvane answer,并回答@Guarav:如果不存在“upsert=True”,则可以添加:

def update_tags(ref, new_tag):
    coll.update({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True)

或者

def update_tags(ref, new_tag):
    coll.update_one({'ref': ref}, {'$push': {'tags': new_tag}}, upsert = True)

您不需要首先使用检索文档,只需使用带^{}运算符的.update方法。

def update_tags(ref, new_tag):
    coll.update({'ref': ref}, {'$push': {'tags': new_tag}})

由于不推荐使用update,如果您使用的是pymongo 2.9或更新版本,那么应该使用^{}^{}方法

你可以简单地

1)如果要附加单个条目

def update_tags(ref, new_tag):
    coll.update({'ref': ref}, {'$push': {'tags': new_tag}})

例如:

{
    "_id" : ObjectId("561c199e038e42b10956e3fc"),
    "tags" : [ "tag1", "tag2", "tag3" ],
    "ref" : "4780"
}
>> update_tags("4780", "tag4")
{'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1}
>> coll.find_one({"ref":"4780"})
{
    "_id" : ObjectId("561c199e038e42b10956e3fc"),
    "tags" : [ "tag1", "tag2", "tag3" , "tag4" ],
    "ref" : "4780"
}

2)如果要附加多个条目

def update_tags(ref, new_tag):
    coll.update({'ref': ref}, {'$pushAll': {'tags': new_tag}}) #type of new_tag is list

例如:

{
    "_id" : ObjectId("561c199e038e42b10956e3fc"),
    "tags" : [ "tag1", "tag2", "tag3" ],
    "ref" : "4780"
}
>> update_tags("4780", ["tag5", "tag6", "tag7"])
{'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1}
>> coll.find_one({"ref":"4780"})
{
    "_id" : ObjectId("561c199e038e42b10956e3fc"),
    "tags" : [ "tag1", "tag2", "tag3" , "tag4" , "tag5", "tag6", "tag7" ],
    "ref" : "4780"
}

注意:如果密钥不存在,那么mongo将创建新密钥。

相关问题 更多 >