MongoDB Generates Same ObjectID for Duplicate Documents












0















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.










share|improve this question























  • Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

    – Jay
    Jan 19 at 13:53
















0















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.










share|improve this question























  • Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

    – Jay
    Jan 19 at 13:53














0












0








0








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.










share|improve this question














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.







mongodb jupyter-notebook pymongo






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 19 at 3:14









warnerm06warnerm06

375




375













  • Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

    – Jay
    Jan 19 at 13:53



















  • Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

    – Jay
    Jan 19 at 13:53

















Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

– Jay
Jan 19 at 13:53





Can you paste the code based on which you get the duplicate key error? Also, is the collection indexed on some fields?

– Jay
Jan 19 at 13:53












1 Answer
1






active

oldest

votes


















0














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/






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54263771%2fmongodb-generates-same-objectid-for-duplicate-documents%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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/






    share|improve this answer




























      0














      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/






      share|improve this answer


























        0












        0








        0







        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/






        share|improve this answer













        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/







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 19 at 13:58









        JayJay

        14.4k2163120




        14.4k2163120






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54263771%2fmongodb-generates-same-objectid-for-duplicate-documents%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Liquibase includeAll doesn't find base path

            How to use setInterval in EJS file?

            Petrus Granier-Deferre