Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在MongoDB 4.2中更新或插入文档的最快方法_Mongodb_Pymongo_Bulkinsert_Insert Update_Upsert - Fatal编程技术网

在MongoDB 4.2中更新或插入文档的最快方法

在MongoDB 4.2中更新或插入文档的最快方法,mongodb,pymongo,bulkinsert,insert-update,upsert,Mongodb,Pymongo,Bulkinsert,Insert Update,Upsert,假设MongoDB集合包含必须定期使用新字段或子对象更新的文档;或者,如果文件尚不存在,则常规文件更新过程应插入新文件(典型的upsert) 实现这一目标的最快方法是什么?目前,我有一个非常缓慢的三阶段过程: 阶段1:根据包含其customID的列表查找必须更新的文档(customID字段上存在索引) 阶段2:在阶段1中检索到的游标中迭代文档,使用新字段和/或子对象丰富文档。将由于尚未在数据库中而无法更新的新文档添加到同一文档列表中 阶段3:使用无序批量操作向上插入MongoDB

假设MongoDB集合包含必须定期使用新字段或子对象更新的文档;或者,如果文件尚不存在,则常规文件更新过程应插入新文件(典型的upsert)

实现这一目标的最快方法是什么?目前,我有一个非常缓慢的三阶段过程:

阶段1:根据包含其customID的列表查找必须更新的文档(customID字段上存在索引)

阶段2:在阶段1中检索到的游标中迭代文档,使用新字段和/或子对象丰富文档。将由于尚未在数据库中而无法更新的新文档添加到同一文档列表中

阶段3:使用无序批量操作向上插入MongoDB

        bulk_mapping = db[myCollection].initialize_unordered_bulk_op()
        for key, value in enrichedDocs.items():
            bulk_mapping.find({'customID': key}).upsert().update({'$set': {'customID': key, 'enrichedBody': value['enrichedBody']}})
        bulk_mapping.execute()

您不需要先
.find()
然后
.update()
,您可以直接使用
upsert
选项执行
update

试试这个:

bulk_mapping = db[myCollection].initialize_unordered_bulk_op()
for key, value in enrichedDocs.items():
    bulk_mapping.update({
        'customID': key
    },{
        '$set': {
            'customID': key, 
            'enrichedBody': value['enrichedBody']
        }
    },upsert=True)
bulk_mapping.execute()
更新

您可以在pymongo中使用以下代码来实现批量更新:

from pymongo import UpdateOne

bulk_operations=[]
for key, value in enrichedDocs.items():
    bulk_operations.append(
        UpdateOne({
            'customID': key
        },{
            '$set': {
                'customID': key, 
                'enrichedBody': value['enrichedBody']
            }
        },upsert=True)
    )

db[myCollection].bulk_write(bulk_operations);

非常感谢。除此之外,还有其他改进或其他方法吗?除此之外,我认为您必须在for循环中逐个执行,这不是一个很好的方法。它会产生一个错误:AttributeError:'BulkOperationBuilder'对象没有属性'update'。upsert参数不能作为PyMongo中的字典传递,但作为一种选择:请更正您的答案以反映这一点。否则,您提出的方法似乎比我问题中描述的方法快13%。在你更正答案后,我将很乐意接受。我更新了我的答案。谢谢你纠正我。我很少用pymongo
from pymongo import UpdateOne

bulk_operations=[]
for key, value in enrichedDocs.items():
    bulk_operations.append(
        UpdateOne({
            'customID': key
        },{
            '$set': {
                'customID': key, 
                'enrichedBody': value['enrichedBody']
            }
        },upsert=True)
    )

db[myCollection].bulk_write(bulk_operations);