Reputation: 814
I'm new to MongoDB and am using Pymongo in a Jupyter Notebook. When inserting a document the first time it works fine. When inserting the same document(rerunning a same jupyter cell) I get a "DuplicateKeyError: E11000 duplicate key error index".
When I instantiate the same User object again, it inserts just fine. I'm new to classes as well. I'm trying to understand why this error occurs.
My understanding is Mongo creates the OjbectID based on time and randomness. This is acting as though the ObjectID is based on when my object was instantiated.
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)
Expected behavior: Create a new Document and unique ObjectID each time a cell is reran.
Actual behavior: Works the first time a cell is ran. Errors on a second run. If User class is called again(with same info) it works.
Upvotes: 1
Views: 1803
Reputation: 24905
The reason why you get this error is because, you are trying to insert a new document with the a value for an indexed key (where the indexed key is marked as Unique) which is already present in one of the documents in MongoDB.
If you have not indexed any of the keys explicitly, then you must including the "_id" field also in your document while inserting and the "_id" field must be having the same value as the previously inserted document.
Please go through the below links:
https://docs.mongodb.com/manual/core/index-unique/
https://docs.mongodb.com/manual/indexes/
Upvotes: 1