【问题标题】:Pymongo not modifying all matching documentsPymongo 没有修改所有匹配的文档
【发布时间】:2021-12-04 11:25:15
【问题描述】:

我正在尝试使用 pymongo 3.12 更新大约 10 万个文档。我相信我正确使用了 pymongo api,但是每次我运行批量写入时;它只更新大约一半与之匹配的文档。

upserts = [UpdateOne({'_id': event["$set"]["metaData"]["id"]}, {'$set': event["$set"]}, upsert=True)
                   for event in events_update_data]
result = cursor.bulk_write(upserts, ordered=False)
print(result.bulk_api_result)

结果:

{'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 427, 'nMatched': 116940, 'nModified': 43303, 'nRemoved': 0, 'upserted': removed_by_me}

那么为什么它与我需要的所有文档都匹配,但只修改了一半?我必须多次运行它才能更新所有文档,并且一致性差异很大。这是每个文档的操作。

data = {"$set": {f'inventoryData.{self.parse_time}': event.pop("inventory"), 'metaData': event}}

我还尝试了不同的 upserting 变体。全部重现相同的结果。

bulk_operations = cursor.initialize_unordered_bulk_op()
    for event in events_update_data:
        bulk_operations.find({'_id':  event["$set"]["metaData"]["id"]}).upsert().update({"$set": event["$set"]})
        result = bulk_operations.execute()
        print(result)

        upserts = []
        for event in events_update_data:
            upserts.append(UpdateOne({'_id': event["$set"]["metaData"]["id"]}, {'$set': event["$set"]}, upsert=True))
            if len(upserts) == 1000:
                try:
                    result = cursor.bulk_write(upserts, ordered=False)
                    upserts = []
                except BulkWriteError as e:
                    print(e.details)
                print(result.bulk_api_result)

【问题讨论】:

    标签: python python-3.x pymongo pymongo-3.x


    【解决方案1】:

    如果您的nMatched 高于您的nModified,那么您的“更新”很可能与原始记录相同,因此未修改。

    【讨论】:

    • 是否有一些语法可以用来强制它更新数据,即使它与原始文档没有变化?它每小时存储一次数据,但不管它是否比前一个小时有所变化,都需要存储它,谢谢
    • 不知道你为什么想要,但也许replace_one / (bulk) ReplaceOne pymongo.readthedocs.io/en/stable/api/pymongo/…?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多