MongoDB为重复的文档生成相同的ObjectID

时间:2019-01-19 03:15:00

标签: mongodb jupyter-notebook pymongo

我是MongoDB的新手,正在Jupyter Notebook中使用Pymongo。首次插入文档时,它可以正常工作。当插入相同的文档时(运行相同的jupyter单元),我得到“ DuplicateKeyError:E11000重复键错误索引”。

当我再次实例化相同的User对象时,它插入就很好。我也是班上的新手。我试图了解为什么会发生此错误。

我的理解是Mongo根据时间和随机性创建OjbectID。这就像ObjectID基于实例化我的对象的时间一样。

class User:
    def __init__(self, email, password, username=None, image_file=None):
        self.email = email
        self.password = password
        self.username = username
        self.image_file = image_file

        self.newUser= f"""{{"email":"{self.email}",
                        "password":"{self.password}", 
                        "username": "{self.username}",
                        "image_file": "{self.image_file}"}}"""
        self.jsonDoc = json.loads(self.newUser)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', 
                      '{self.image_file}')"

jim = User("xx2", "password")
mongo.db.users.insert_one(jim.jsonDoc)

预期的行为:每次重新运行单元格时,都会创建一个新的Document和唯一的ObjectID。

实际行为:第一次运行单元格时有效。第二次运行时出错。如果再次调用User类(具有相同的信息),它将起作用。

1 个答案:

答案 0 :(得分:0)

出现此错误的原因是,您试图插入一个新文档,该文档的索引键的值(其中索引键标记为唯一)已存在于MongoDB的其中一个文档中

如果尚未显式索引任何键,则在插入文档时还必须在文档中包括“ _id”字段,并且“ _id”字段的值必须与先前插入的文档相同。

请通过以下链接:

https://docs.mongodb.com/manual/core/index-unique/

https://docs.mongodb.com/manual/indexes/