MongoDB: невозможно вставить дважды один и тот же документ

В моем коде pymongo при вставке дважды одного и того же документа возникает ошибка:

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

повышает:

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

вставка двух документов с различным содержанием работает нормально.

Похоже, в соответствии с https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/ Я должен сделать что-то еще вариант индексов:

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.

2 ответа

Добавляя к ответу Пебы, вы можете использовать .copy() метод словаря Python, чтобы избежать мутации самого документа.

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

Таким образом, каждый insert_one вызов получить мелкую копию document и в то же время сохраняет ваш код более питонным.

Вставка документа неявно генерирует _id, Таким образом, после вставки документа он будет видоизменяться

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

Попытка вставить указанный документ снова приведет к ошибке из-за дублирования _id,

Вы можете создать новый документ с теми же значениями и вставить его.

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)
Другие вопросы по тегам