2
votes

So a little background, I've 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 into my collection I just get an error off:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "[email protected]" }

I have been looking around on the internet for a solution both in python but also 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":"[email protected]", "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 fields to have a unique or am I misunderstanding the processes?

Im using the latest version of pymongo.

1

1 Answers

2
votes

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "[email protected]" }

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()