问题描述
有点背景知识,我之前在 node.js 和 mongoose.js 中使用过 MongoDB.现在我决定尝试使用 python 和 pymongo.但是当我尝试将一个文档插入到我的收藏中时,我却得到了一个错误:
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]" }
我一直在互联网上四处寻找 Python 和其他语言的解决方案.这很可能是因为 iv 之前只使用 mongoose.js 与 mongo 交谈,而我可能无法完全掌握 MongoDB 的基础知识.
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.
来自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)
来自 Post.py
from model import Model
class Post(Model):
collection_name = "emails"
def __init__(self):
super(Post, self).__init__()
在 app.py 中我只是做
And in app.py I just do
from models.Post import Post
post = Post()
post.save({"email":"[email protected]", "name":"bob"})
当数据库中没有文档时,它插入正常.但是,如果我再次尝试插入相同的内容,则会出现 DuplicateKeyError.好像 MongoDB 期望所有字段都具有唯一性,还是我误解了流程?
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?
我使用的是最新版本的 pymongo.
Im using the latest version of pymongo.
推荐答案
根据错误判断,您实际上为 email
字段定义了一个唯一索引.
Judging by the error, you actually have a unique index defined for the email
field.
仅供参考,您可以使用index_information()
方法:
FYI, you can get the index information using index_information()
method:
self.collection.index_information()
这篇关于pymongo 获取 E11000 重复键错误索引 pymongo 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!