Python 将项附加到PyMongo中的MongoDB文档数组,而无需重新插入

Python 将项附加到PyMongo中的MongoDB文档数组,而无需重新插入,python,mongodb,mongodb-query,pymongo,Python,Mongodb,Mongodb Query,Pymongo,我使用MongoDB作为Python web应用程序(PyMongo+Battle)的后端数据库。用户可以上传文件,并在上传过程中选择性地“标记”这些文件。标签作为列表存储在文档中,如下所示: { "_id" : ObjectId("561c199e038e42b10956e3fc"), "tags" : [ "tag1", "tag2", "tag3" ], "ref" : "4780" } 我试图允许用户将新标签附加到任何文档中。我想出了这样的办法: def upd

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

{
    "_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
键始终是唯一的。这也可能是
\u id
) 似乎应该有一种方法可以直接更新“tags”值,而无需收回整个文档并重新插入。我是不是遗漏了什么


非常感谢您的任何想法:)

您不需要先使用来检索文档,只需与操作员一起使用
.update
方法即可

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

由于不推荐使用更新,如果您正在使用pymongo 2.9或更新版本,则应使用或方法来添加到@ssytvane answer,并回答@Guarav:如果不存在,则可以添加“upsert=True”:

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

你可以简单地做

1) 如果要附加单个条目

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

2) 如果要附加多个条目

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


注意:如果密钥尚未存在,则mongo将创建新密钥。

有一些正确的答案,但我认为以这种方式编写更新标记更好、更有用:

def update_tags(ref, *args):
    coll.update_one(ref, {'$push': {'tags': {'$each': args}}})
这样,您既可以附加一个标记,也可以附加多个标记:

>> update_tags(ref, 'tag5')

您可以使用
$push

collection_name.update_one({'ref': ref}, {'$push': {'tags': new_tag}})
您可以在一个查询中更新多个数组

collection_name.update_one({'ref': ref}, {'$push': {'field1': value1, 'filed2': value2}})
可以按如下方式推送值

{ $push: { <field1>: <value1>, ... } }
{$push:{:,…}

两者之间有什么区别?仅返回值(文档与UpdateResult对象)?何时使用一个或另一个?如果“标记”字段不存在会发生什么情况?如果
标记
字段不存在,则创建该字段@Gauravojawa是否删除旧记录?必须是数组,但文档中的类型为object。此错误pops UPPYMOGO.errors.WRITEEROR:未知修饰符:$pushAll
$pushAll
不适用于向数组追加多个值。使用
$push
$each
修饰符将多个值附加到数组字段<代码>{'push':{'tags':{'each':new_tags_array}}}
这里的ref是什么?
>> update_tags(ref, 'tag5', 'tag6')
>> list_of_new_tags = do_something_that_returns_list_of_tags()
>> update_tags(ref, *list_of_new_tags)
collection_name.update_one({'ref': ref}, {'$push': {'tags': new_tag}})
collection_name.update_one({'ref': ref}, {'$push': {'field1': value1, 'filed2': value2}})
{ $push: { <field1>: <value1>, ... } }