指点成金-最美分享吧

登录

在pymongo的update_one()中出现重复键错误

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了在pymongo的update_one()中出现重复键错误相关的知识,希望对你有一定的参考价值。

这里我使用了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 MongoClientdb = MongoClient()collection = db.tests.testscollection.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)

你必须从语义上改变使用两个字段。或者你可以改变默认的主键。

以上是关于在pymongo的update_one()中出现重复键错误的主要内容,如果未能解决你的问题,请参考以下文章