E11000 duplicate key error index pymongo

情到浓时终转凉″ 提交于 2020-01-06 03:36:50

问题


So a little background, Ive worked with mongodb before in node.js with mongoose.js. And now I decided to try out to work with python and pymongo. But when I try to insert a document in to my collection I just get a error off:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }

I have been looking araund on the internet for a solution both in python but allso in other languages. It might very well be that sense iv only used mongoose.js to talk to mongo before and that I might not fully grasp the basics off mongodb.

From model.py

from pymongo import MongoClient

class Model(object):
    client = MongoClient()
    db = client["database"]
    collection_name = ""

    def __init__(self):
        self.collection = self.db[self.collection_name]

    def save(self, data):
        self.collection.insert_one(data)

From Post.py

from model import Model

class Post(Model):

    collection_name = "emails"

    def __init__(self):
        super(Post, self).__init__()

And in app.py I just do

from models.Post import Post

post = Post()
post.save({"email":"mail@example.com", "name":"bob"})

When there is no document in the database it inserts fine. But if I try to insert the same again I get the DuplicateKeyError. It is as if mongodb expects all the feilds to have a unique or im I misunderstanding the processes?

Im using the latest version of pymongo.


回答1:


pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }

Judging by the error, you actually have a unique index defined for the email field.

FYI, you can get the index information using index_information() method:

self.collection.index_information()


来源:https://stackoverflow.com/questions/36649794/e11000-duplicate-key-error-index-pymongo

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