ReplaceOne 如果查询匹配,InsertOne 如果文档不存在

ReplaceOne if query matches, InsertOne if document does not exist

我正在尝试使用 pymongo 编写一个数据迁移脚本

  1. ReplaceOne 如果 {'_id': id, 'array.0':{'$exists':False} } 匹配
  2. InsertOne 如果具有给定 id 的文档不存在,即 not 检查 'array.0':{'$exists':False}

目前脚本是这样的

from pymongo import ReplaceOne

def replace_one(row, id):
    return ReplaceOne({'_id': id, 'array.0':{'$exists':False} }, row, upsert=True)

这可能会导致重复键错误,因为 upsert=True 会在查询不匹配且具有查询 ID 的文档已存在时尝试创建文档。但是我只想在文档不存在的情况下创建文档。

另一个要求是我不想使用更新,因为当你有很多行时它会慢得多。

从您的代码看来,您正在使用批量运算符。

您需要使用的是UpdateOne(),然后在批量写入时添加ordered=False参数。这将尝试更新,但忽略任何错误(即重复错误)。

UpdateOne 没有理由比您的示例中的 ReplaceOne 慢。

https://pymongo.readthedocs.io/en/stable/examples/bulk.html#unordered-bulk-write-operations