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

Fastest way of updating or alternatively inserting documents in MongoDB 4.2

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

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

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

        db[myCollection].find({'customID': {'$in': myUpdateList}})

第 2 阶段:迭代第 1 阶段检索到的游标中的文档,用新字段 and/or 子对象丰富它们。将尚未在数据库中的新文档添加到同一文档列表中。

第 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);