这里我使用了pymongo的upsert=True update_one()。
预期的结果是,如果条目已经存在,就应该合并,但这个命令的结果是重复键错误,逻辑上 "uniqueId "和"_id "是主键,但我没有手动设置任何东西,所以只有_id是。但我没有手动设置任何东西,所以只有_id是。
db.alerts.update_one({"uniqueId":doc['uniqueId']},{"$set":doc,"$max":statusDict,"$min":{"_id":newId}},upsert=True)
Error.逻辑上 "uniqueId "和"_id "是主键,但我没有手动设置任何东西,所以只有_id是。
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'
在 update_one 中,我们可以改变或添加主键以外的属性,主键是 dafault '_id'。
在我的例子中,我把_id和uniqueId的用法换了一下。然后代码就工作了。
对于这个简单的例子,只需用do来交换这两个属性就可以了。
collection.update_one({"_id":1},{"$set":{"name":"jerry"},"$min":{"unique":0}})
你必须从语义上改变使用两个字段。或者你可以改变默认的主键。