Mongo批量更新不工作

2024-09-24 00:32:27 发布

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

我试图在我的MongoDB上运行一些更新操作。我想使用指定的大容量更新操作here,但是使用pymongo这对我不起作用。我的代码如下

import pymongo

client = pymongo.MongoClient()
db = client.test
bulk = db.testCol.initialize_unordered_bulk_op();
bulk.find({"_id":"1,1,1"}).update({"$set":{"attr1":1, "attr2":"X", "attr3":99}})
print bulk.execute()

其输出为:

^{pr2}$

据我所知,Mongo正在查找文档(nMatched=1),但没有更新它(nModified=0)。我不明白它为什么这么做。在

当我在不使用Bulk的情况下手动执行操作时,输出似乎是正确的,并且记录会根据请求进行修改。 代码:

import pymongo

client = pymongo.MongoClient()
db = client.test
print db.testCol.update({"_id":"1,1,1"}, {"attr1":1, "attr2":"X", "attr3":99})

这样做是可行的,无论是打印还是数据库的内容。在

{'updatedExisting': True, u'nModified': 1, u'ok': 1, u'n': 1}

我不知道我做错了什么。据我所知,我遵循了执行批量更新的正确过程。在


Tags: 代码testimportclientiddbupdatebulk
1条回答
网友
1楼 · 发布于 2024-09-24 00:32:27

我创建了一个实用函数来进行批量更新。在

def bulk_update(db, collection_name, update_set_where_list):
    """

    :param db: pymongo.database.Database Object
    :param collection_name: Collection name
    :param update_set_where_list:
    :return: full result dictionary
    """
    required_keys = ["where", "set"]
    bulk = db[collection_name].initialize_unordered_bulk_op()

    for update_where_set in update_set_where_list:
        if all(key in update_where_set for key in required_keys):
             bulk.find(update_where_set["where"]).update({"$set": update_where_set["set"]})
        else:
            raise Exception("Required key missing. {}".format(required_keys))

    return bulk.execute()

例如,假设test数据库中的myCollection集合需要更新为y=3,其中x=1,y=6,x=5。在

那么对实用函数的调用如下所示

^{pr2}$

相关问题 更多 >