Get _id of an inserted document in MongoDB?












24















say I have a product listing. When I add a new product I save it using something like



var doc=products.Insert<ProductPDO>(p);


The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>



However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.



Is there an easier way? (also, doc in this instance returns null for some reason)










share|improve this question



























    24















    say I have a product listing. When I add a new product I save it using something like



    var doc=products.Insert<ProductPDO>(p);


    The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>



    However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.



    Is there an easier way? (also, doc in this instance returns null for some reason)










    share|improve this question

























      24












      24








      24


      0






      say I have a product listing. When I add a new product I save it using something like



      var doc=products.Insert<ProductPDO>(p);


      The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>



      However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.



      Is there an easier way? (also, doc in this instance returns null for some reason)










      share|improve this question














      say I have a product listing. When I add a new product I save it using something like



      var doc=products.Insert<ProductPDO>(p);


      The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>



      However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.



      Is there an easier way? (also, doc in this instance returns null for some reason)







      c# mongodb mongodb-.net-driver






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 3 '11 at 8:06









      EarlzEarlz

      31.1k77242460




      31.1k77242460
























          4 Answers
          4






          active

          oldest

          votes


















          38














          You can check the id field of the inserted document. It should be filled in.



          Edited by asker:



          Just to be clear, in order to make an id field in your own classes you just use:



          [BsonId]
          public ObjectId ID{get;set;}





          share|improve this answer


























          • for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

            – Vincent Buscarello
            Sep 7 '18 at 19:02



















          13














          When you insert an object into the mongodb, mongo will update the object with the internal ID.



          So if



          data = {
          title: "Howdy"
          }


          Then when we insert the data object into the db



          db.collection('collectionName', function(err, collection) {
          collection.insert(data);
          console.log(data._id); // <- The mongodb id is now set on the item
          });





          share|improve this answer































            3














            As the comment above, add the fild ID in your model with



            [BsonId]
            [BsonRepresentation(BsonType.ObjectId)]
            public string id { get; set; }


            using:



            using MongoDB.Bson;
            using MongoDB.Bson.Serialization.Attributes;


            and then when you insert the object, mongo return the ID of the document into the fild ID of the model.






            share|improve this answer































              0














              If you know the type of ID you can do something like this:



              public static TId GetId<TId>(this BsonDocument document) where TId : struct
              {
              if (document == default(BsonDocument))
              {
              throw new ArgumentNullException("document");
              }

              var id = document["_id"];

              object idAsObject;

              if (id.IsGuid)
              {
              idAsObject = (object)id.AsGuid;
              }
              else if (id.IsObjectId)
              {
              idAsObject = (object)id.AsObjectId;
              }
              else
              {
              throw new NotImplementedException(string.Format("Unknown _id type "{0}"", id.BsonType));
              }

              var idCasted = (TId)idAsObject;

              return idCasted;
              }


              Use it like this:



              Guid idOfDoc = myBsonDocument.GetId<Guid>();


              Still you should prefere have a dedicated property as in the chosen answer...






              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%2f4582912%2fget-id-of-an-inserted-document-in-mongodb%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                38














                You can check the id field of the inserted document. It should be filled in.



                Edited by asker:



                Just to be clear, in order to make an id field in your own classes you just use:



                [BsonId]
                public ObjectId ID{get;set;}





                share|improve this answer


























                • for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                  – Vincent Buscarello
                  Sep 7 '18 at 19:02
















                38














                You can check the id field of the inserted document. It should be filled in.



                Edited by asker:



                Just to be clear, in order to make an id field in your own classes you just use:



                [BsonId]
                public ObjectId ID{get;set;}





                share|improve this answer


























                • for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                  – Vincent Buscarello
                  Sep 7 '18 at 19:02














                38












                38








                38







                You can check the id field of the inserted document. It should be filled in.



                Edited by asker:



                Just to be clear, in order to make an id field in your own classes you just use:



                [BsonId]
                public ObjectId ID{get;set;}





                share|improve this answer















                You can check the id field of the inserted document. It should be filled in.



                Edited by asker:



                Just to be clear, in order to make an id field in your own classes you just use:



                [BsonId]
                public ObjectId ID{get;set;}






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 3 '11 at 8:26









                Earlz

                31.1k77242460




                31.1k77242460










                answered Jan 3 '11 at 8:11









                Scott HernandezScott Hernandez

                6,39212825




                6,39212825













                • for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                  – Vincent Buscarello
                  Sep 7 '18 at 19:02



















                • for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                  – Vincent Buscarello
                  Sep 7 '18 at 19:02

















                for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                – Vincent Buscarello
                Sep 7 '18 at 19:02





                for those newer to .NET this is still not clear. In what c sharp object can I extract the new ID? can you post example code?

                – Vincent Buscarello
                Sep 7 '18 at 19:02













                13














                When you insert an object into the mongodb, mongo will update the object with the internal ID.



                So if



                data = {
                title: "Howdy"
                }


                Then when we insert the data object into the db



                db.collection('collectionName', function(err, collection) {
                collection.insert(data);
                console.log(data._id); // <- The mongodb id is now set on the item
                });





                share|improve this answer




























                  13














                  When you insert an object into the mongodb, mongo will update the object with the internal ID.



                  So if



                  data = {
                  title: "Howdy"
                  }


                  Then when we insert the data object into the db



                  db.collection('collectionName', function(err, collection) {
                  collection.insert(data);
                  console.log(data._id); // <- The mongodb id is now set on the item
                  });





                  share|improve this answer


























                    13












                    13








                    13







                    When you insert an object into the mongodb, mongo will update the object with the internal ID.



                    So if



                    data = {
                    title: "Howdy"
                    }


                    Then when we insert the data object into the db



                    db.collection('collectionName', function(err, collection) {
                    collection.insert(data);
                    console.log(data._id); // <- The mongodb id is now set on the item
                    });





                    share|improve this answer













                    When you insert an object into the mongodb, mongo will update the object with the internal ID.



                    So if



                    data = {
                    title: "Howdy"
                    }


                    Then when we insert the data object into the db



                    db.collection('collectionName', function(err, collection) {
                    collection.insert(data);
                    console.log(data._id); // <- The mongodb id is now set on the item
                    });






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 14 '12 at 6:22









                    Shaheen GhiassyShaheen Ghiassy

                    5,14223237




                    5,14223237























                        3














                        As the comment above, add the fild ID in your model with



                        [BsonId]
                        [BsonRepresentation(BsonType.ObjectId)]
                        public string id { get; set; }


                        using:



                        using MongoDB.Bson;
                        using MongoDB.Bson.Serialization.Attributes;


                        and then when you insert the object, mongo return the ID of the document into the fild ID of the model.






                        share|improve this answer




























                          3














                          As the comment above, add the fild ID in your model with



                          [BsonId]
                          [BsonRepresentation(BsonType.ObjectId)]
                          public string id { get; set; }


                          using:



                          using MongoDB.Bson;
                          using MongoDB.Bson.Serialization.Attributes;


                          and then when you insert the object, mongo return the ID of the document into the fild ID of the model.






                          share|improve this answer


























                            3












                            3








                            3







                            As the comment above, add the fild ID in your model with



                            [BsonId]
                            [BsonRepresentation(BsonType.ObjectId)]
                            public string id { get; set; }


                            using:



                            using MongoDB.Bson;
                            using MongoDB.Bson.Serialization.Attributes;


                            and then when you insert the object, mongo return the ID of the document into the fild ID of the model.






                            share|improve this answer













                            As the comment above, add the fild ID in your model with



                            [BsonId]
                            [BsonRepresentation(BsonType.ObjectId)]
                            public string id { get; set; }


                            using:



                            using MongoDB.Bson;
                            using MongoDB.Bson.Serialization.Attributes;


                            and then when you insert the object, mongo return the ID of the document into the fild ID of the model.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 26 '17 at 15:15









                            Jorge Barraza ZJorge Barraza Z

                            614




                            614























                                0














                                If you know the type of ID you can do something like this:



                                public static TId GetId<TId>(this BsonDocument document) where TId : struct
                                {
                                if (document == default(BsonDocument))
                                {
                                throw new ArgumentNullException("document");
                                }

                                var id = document["_id"];

                                object idAsObject;

                                if (id.IsGuid)
                                {
                                idAsObject = (object)id.AsGuid;
                                }
                                else if (id.IsObjectId)
                                {
                                idAsObject = (object)id.AsObjectId;
                                }
                                else
                                {
                                throw new NotImplementedException(string.Format("Unknown _id type "{0}"", id.BsonType));
                                }

                                var idCasted = (TId)idAsObject;

                                return idCasted;
                                }


                                Use it like this:



                                Guid idOfDoc = myBsonDocument.GetId<Guid>();


                                Still you should prefere have a dedicated property as in the chosen answer...






                                share|improve this answer




























                                  0














                                  If you know the type of ID you can do something like this:



                                  public static TId GetId<TId>(this BsonDocument document) where TId : struct
                                  {
                                  if (document == default(BsonDocument))
                                  {
                                  throw new ArgumentNullException("document");
                                  }

                                  var id = document["_id"];

                                  object idAsObject;

                                  if (id.IsGuid)
                                  {
                                  idAsObject = (object)id.AsGuid;
                                  }
                                  else if (id.IsObjectId)
                                  {
                                  idAsObject = (object)id.AsObjectId;
                                  }
                                  else
                                  {
                                  throw new NotImplementedException(string.Format("Unknown _id type "{0}"", id.BsonType));
                                  }

                                  var idCasted = (TId)idAsObject;

                                  return idCasted;
                                  }


                                  Use it like this:



                                  Guid idOfDoc = myBsonDocument.GetId<Guid>();


                                  Still you should prefere have a dedicated property as in the chosen answer...






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    If you know the type of ID you can do something like this:



                                    public static TId GetId<TId>(this BsonDocument document) where TId : struct
                                    {
                                    if (document == default(BsonDocument))
                                    {
                                    throw new ArgumentNullException("document");
                                    }

                                    var id = document["_id"];

                                    object idAsObject;

                                    if (id.IsGuid)
                                    {
                                    idAsObject = (object)id.AsGuid;
                                    }
                                    else if (id.IsObjectId)
                                    {
                                    idAsObject = (object)id.AsObjectId;
                                    }
                                    else
                                    {
                                    throw new NotImplementedException(string.Format("Unknown _id type "{0}"", id.BsonType));
                                    }

                                    var idCasted = (TId)idAsObject;

                                    return idCasted;
                                    }


                                    Use it like this:



                                    Guid idOfDoc = myBsonDocument.GetId<Guid>();


                                    Still you should prefere have a dedicated property as in the chosen answer...






                                    share|improve this answer













                                    If you know the type of ID you can do something like this:



                                    public static TId GetId<TId>(this BsonDocument document) where TId : struct
                                    {
                                    if (document == default(BsonDocument))
                                    {
                                    throw new ArgumentNullException("document");
                                    }

                                    var id = document["_id"];

                                    object idAsObject;

                                    if (id.IsGuid)
                                    {
                                    idAsObject = (object)id.AsGuid;
                                    }
                                    else if (id.IsObjectId)
                                    {
                                    idAsObject = (object)id.AsObjectId;
                                    }
                                    else
                                    {
                                    throw new NotImplementedException(string.Format("Unknown _id type "{0}"", id.BsonType));
                                    }

                                    var idCasted = (TId)idAsObject;

                                    return idCasted;
                                    }


                                    Use it like this:



                                    Guid idOfDoc = myBsonDocument.GetId<Guid>();


                                    Still you should prefere have a dedicated property as in the chosen answer...







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 1 '18 at 12:11









                                    CodingYourLifeCodingYourLife

                                    1,33831632




                                    1,33831632






























                                        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%2f4582912%2fget-id-of-an-inserted-document-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

                                        Ottavio Pratesi

                                        Tricia Helfer

                                        15 giugno