具体报错如下
Traceback (most recent call last):
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: DDbook.book index: _id_ dup key: { _id: "114" }
错误原因:
在使用pymongo存入数据库时,要写入的主键_id(MongoDB默认主键,但是我们要自己写入主键),出现重复值,这里报错时存在一个_id: "114"
,就是说之前数据库其实已经写入了了关于键为“114”
的值,但是我们在存入时再一次使用到该_id
值导致错误。
我们再使用ipython
重现报错:
In [21]: col.find_one()
Out[21]: {'_id': 22, 'name': 'tom'}
In [22]: col.insert_one({'_id': 22, 'name': 'bean'})
---------------------------------------------------------------------------
DuplicateKeyError Traceback (most recent call last)
上面看到,已经插入一次值了,但是再插入时,就会报错!其错误代码:
DuplicateKeyError: E11000 duplicate key error collection: test.test index: _id_ dup key: { _id: 22 }
果然和上面错误相同
解决办法
-
第一种方法:
使用
save
关键字进行覆盖保存。使用ipython
演示如下:In [23]: col.save({'_id': 22, 'name': 'bean'}) <ipython-input-23-328ef8717ccd>:1: DeprecationWarning: save is deprecated. Use insert_one or replace_one instead col.save({'_id': 22, 'name': 'bean'}) Out[23]: 22 In [24]: col.find_one() Out[24]: {'_id': 22, 'name': 'bean'}
痛点:
旧的数据会被覆盖掉
-
第二种方法:
使用try
语句try: col.insert_one({"_id":"xx","name":"xx"}) except: pass
痛点:
额,目前还不知道