MongoDB : Can't insert twice the same document

落花浮王杯 提交于 2019-12-24 10:12:13

问题


On my pymongo code, inserting twice the same doc raises an error :

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document)
collection.insert_one(document)

raises :

DuplicateKeyError: E11000 duplicate key error collection: test.myCollection index: _id_ dup key: { : ObjectId('5aa282eff1dba231beada9e3') }

inserting two documents with different content works fine.

Seems like according to https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options I should do something aobut option of indexes:

unique  boolean 
Optional. Creates a unique index so that the collection will not accept insertion or update of documents where the index key value matches an existing value in the index.

Specify true to create a unique index. The default value is false.

The option is unavailable for hashed indexes.

回答1:


Adding to Peba's answer, you can use the .copy() method of python dictionary to avoid the mutation of the document itself.

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document.copy())
collection.insert_one(document.copy())

This way, each insert_one call get's a shallow copy of the document and at the same time keeps your code more pythonic.




回答2:


Inserting a document implicitly generates an _id. So after inserting the document it will mutate to

document = {"_id" : ObjectId('random_id_here'),
            "auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}

Trying to insert said document again will result in an error due to the duplicated _id.

You can create a new document with the same values and insert it.

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document)

document = {"auteur" : "romain",
            "text" : "premier post",
            "tag" : "test2",
            "date" : datetime.datetime.utcnow()}
collection.insert_one(document)


来源:https://stackoverflow.com/questions/49194284/mongodb-cant-insert-twice-the-same-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!