问题
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