pymongo 获取 E11000 重复键错误索引 pymongo 错误
pymongo getting E11000 duplicate key error index pymongo error
所以有点背景,我之前在 node.js 和 mongoose.js 中与 MongoDB 合作过。现在我决定尝试使用 python 和 pymongo。但是当我尝试将文档插入我的集合时,我只是得到一个错误:
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }
我一直在互联网上寻找 python 和其他语言的解决方案。很可能是感觉 iv 之前只使用 mongoose.js 与 mongo 交谈,而我可能没有完全掌握 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 我只是
from models.Post import Post
post = Post()
post.save({"email":"mail@example.com", "name":"bob"})
当数据库中没有文档时,它会正常插入。但是,如果我再次尝试插入相同的内容,则会出现 DuplicateKeyError。好像 MongoDB 期望所有字段都具有唯一性,还是我误解了流程?
我正在使用最新版本的 pymongo。
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }
根据错误判断,您实际上为 email
字段定义了一个唯一索引。
仅供参考,您可以使用index_information()
方法获取索引信息:
self.collection.index_information()
所以有点背景,我之前在 node.js 和 mongoose.js 中与 MongoDB 合作过。现在我决定尝试使用 python 和 pymongo。但是当我尝试将文档插入我的集合时,我只是得到一个错误:
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }
我一直在互联网上寻找 python 和其他语言的解决方案。很可能是感觉 iv 之前只使用 mongoose.js 与 mongo 交谈,而我可能没有完全掌握 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 我只是
from models.Post import Post
post = Post()
post.save({"email":"mail@example.com", "name":"bob"})
当数据库中没有文档时,它会正常插入。但是,如果我再次尝试插入相同的内容,则会出现 DuplicateKeyError。好像 MongoDB 期望所有字段都具有唯一性,还是我误解了流程?
我正在使用最新版本的 pymongo。
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: database.emails.$email_1 dup key: { : "mail@example.com" }
根据错误判断,您实际上为 email
字段定义了一个唯一索引。
仅供参考,您可以使用index_information()
方法获取索引信息:
self.collection.index_information()