Is there a way to create an ObjectID from INT in MongoDB?Is there a way to run Python on Android?How can I safely create a nested directory in Python?How do I parse a string to a float or int in Python?How to substring a string in Python?Python progression path - From apprentice to guruHow to query MongoDB with “like”?Ways to implement data versioning in MongoDBMongoDB relationships: embed or reference?Fastest way to check if a value exist in a list“Large data” work flows using pandas

Work requires me to come in early to start computer but wont let me clock in to get paid for it

Are there moral objections to a life motivated purely by money? How to sway a person from this lifestyle?

Creating a chemical industry from a medieval tech level without petroleum

Can a level 2 Warlock take one level in rogue, then continue advancing as a warlock?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

Why do real positive eigenvalues result in an unstable system? What about eigenvalues between 0 and 1? or 1?

How much cash can I safely carry into the USA and avoid civil forfeiture?

Unknown code in script

Mistake in years of experience in resume?

What is purpose of DB Browser(dbbrowser.aspx) under admin tool?

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

How long after the last departure shall the airport stay open for an emergency return?

How can I get rid of an unhelpful parallel branch when unpivoting a single row?

Is there a word for the censored part of a video?

A faster way to compute the largest prime factor

Was Dennis Ritchie being too modest in this quote about C and Pascal?

Co-worker works way more than he should

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

Is there a better way to say "see someone's dreams"?

Why do games have consumables?

What does a straight horizontal line above a few notes, after a changed tempo mean?

How to pronounce 'c++' in Spanish

Retract an already submitted recommendation letter (written for an undergrad student)

A strange hotel



Is there a way to create an ObjectID from INT in MongoDB?


Is there a way to run Python on Android?How can I safely create a nested directory in Python?How do I parse a string to a float or int in Python?How to substring a string in Python?Python progression path - From apprentice to guruHow to query MongoDB with “like”?Ways to implement data versioning in MongoDBMongoDB relationships: embed or reference?Fastest way to check if a value exist in a list“Large data” work flows using pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















This question has originally been asked in dba.stackexchange.com. I'm trying to migrate user ids from MySQL to MongoDB and I want to create objectIDs from an int. Is there a way to store INTs inside of ObjectID parts like the random section of ObjectID? Then convert it back to from ObjectID to int.










share|improve this question






























    1















    This question has originally been asked in dba.stackexchange.com. I'm trying to migrate user ids from MySQL to MongoDB and I want to create objectIDs from an int. Is there a way to store INTs inside of ObjectID parts like the random section of ObjectID? Then convert it back to from ObjectID to int.










    share|improve this question


























      1












      1








      1








      This question has originally been asked in dba.stackexchange.com. I'm trying to migrate user ids from MySQL to MongoDB and I want to create objectIDs from an int. Is there a way to store INTs inside of ObjectID parts like the random section of ObjectID? Then convert it back to from ObjectID to int.










      share|improve this question
















      This question has originally been asked in dba.stackexchange.com. I'm trying to migrate user ids from MySQL to MongoDB and I want to create objectIDs from an int. Is there a way to store INTs inside of ObjectID parts like the random section of ObjectID? Then convert it back to from ObjectID to int.







      python mongodb pymongo objectid






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 10 at 11:00







      ALH

















      asked Mar 9 at 7:40









      ALHALH

      2,23543080




      2,23543080






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Ok, there is straightforward approach:



          import bson

          def object_id_from_int(n):
          s = str(n)
          s = '0' * (24 - len(s)) + s
          return bson.ObjectId(s)

          def int_from_object_id(obj):
          return int(str(obj))

          n = 12345
          obj = object_id_from_int(n)
          n = int_from_object_id(obj)
          print(repr(obj)) # ObjectId('000000000000000000012345')
          print(n) # 12345





          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%2f55075128%2fis-there-a-way-to-create-an-objectid-from-int-in-mongodb%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









            1














            Ok, there is straightforward approach:



            import bson

            def object_id_from_int(n):
            s = str(n)
            s = '0' * (24 - len(s)) + s
            return bson.ObjectId(s)

            def int_from_object_id(obj):
            return int(str(obj))

            n = 12345
            obj = object_id_from_int(n)
            n = int_from_object_id(obj)
            print(repr(obj)) # ObjectId('000000000000000000012345')
            print(n) # 12345





            share|improve this answer





























              1














              Ok, there is straightforward approach:



              import bson

              def object_id_from_int(n):
              s = str(n)
              s = '0' * (24 - len(s)) + s
              return bson.ObjectId(s)

              def int_from_object_id(obj):
              return int(str(obj))

              n = 12345
              obj = object_id_from_int(n)
              n = int_from_object_id(obj)
              print(repr(obj)) # ObjectId('000000000000000000012345')
              print(n) # 12345





              share|improve this answer



























                1












                1








                1







                Ok, there is straightforward approach:



                import bson

                def object_id_from_int(n):
                s = str(n)
                s = '0' * (24 - len(s)) + s
                return bson.ObjectId(s)

                def int_from_object_id(obj):
                return int(str(obj))

                n = 12345
                obj = object_id_from_int(n)
                n = int_from_object_id(obj)
                print(repr(obj)) # ObjectId('000000000000000000012345')
                print(n) # 12345





                share|improve this answer















                Ok, there is straightforward approach:



                import bson

                def object_id_from_int(n):
                s = str(n)
                s = '0' * (24 - len(s)) + s
                return bson.ObjectId(s)

                def int_from_object_id(obj):
                return int(str(obj))

                n = 12345
                obj = object_id_from_int(n)
                n = int_from_object_id(obj)
                print(repr(obj)) # ObjectId('000000000000000000012345')
                print(n) # 12345






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 9 at 17:32

























                answered Mar 9 at 17:26









                SanyashSanyash

                3,08621230




                3,08621230





























                    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%2f55075128%2fis-there-a-way-to-create-an-objectid-from-int-in-mongodb%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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved