1

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.
Romain Jouin
  • 4,448
  • 3
  • 49
  • 79

2 Answers2

2

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.

Sreenadh T C
  • 592
  • 2
  • 17
0

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)
Peba
  • 440
  • 4
  • 14
  • that's strange. And the error disapear with the "save" method, which I use now (but is deprecated) – Romain Jouin Mar 09 '18 at 13:54
  • @romainjouin The save method is doing an upsert if an `_id`is already present in the document, so it's replacing the existing document instead of creating a new one. You can find more at [the docs](https://docs.mongodb.com/manual/reference/method/db.collection.save). I advise to not use it tho, and go for the non deprecated alternatives `insert_one()` or `replace_one()` instead. – Peba Mar 09 '18 at 14:08