【发布时间】:2020-09-12 06:15:31
【问题描述】:
这里我使用 pymongo 的 update_one() 和 upsert=True。
预期的结果是如果条目已经存在,它应该合并。 但是这个命令会导致 Duplicate Key Error。 逻辑上“uniqueId”和“_id”是主键。但我没有手动设置任何东西,所以只有 _id 是。
db.alerts.update_one({"uniqueId":doc['uniqueId']},{"$set":doc,"$max":statusDict,"$min":{"_id":newId}},upsert=True)
错误:
E11000 duplicate key error collection: alerts.alerts index: _id_ dup key: { _id: "336" }
这不是 update_one() 所期望的,对吧?
案例的简化示例
from pymongo import MongoClient
db = MongoClient()
collection = db.tests.tests
collection.insert_one({"name":"tom","unique":1,"_id":1})
collection.update_one({"unique":1},{"$set":{"name":"jerry"},"$min":{"_id":0}})
这会产生错误_id字段
pymongo.errors.WriteError: Performing an update on the path '_id' would modify the immutable field '_id'
【问题讨论】:
-
str演员表是怎么回事? -
@D.SM 实际上不是必需的。但无论如何,它没有任何作用
-
如果不需要,请取出。比较会考虑类型。
-
@D.SM 谢谢。我已经把它拿出来了。错误仍然存在
-
好的,接下来减少您的示例,使其包含插入数据和执行更新的代码,但更新失败。