Get _id of an inserted document in MongoDB?
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
add a comment |
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
add a comment |
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
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
c# mongodb mongodb-.net-driver
asked Jan 3 '11 at 8:06
EarlzEarlz
31.1k77242460
31.1k77242460
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
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;}
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
add a comment |
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
});
add a comment |
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.
add a comment |
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...
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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;}
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
add a comment |
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;}
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
add a comment |
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;}
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;}
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
add a comment |
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
add a comment |
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
});
add a comment |
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
});
add a comment |
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
});
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
});
answered Dec 14 '12 at 6:22
Shaheen GhiassyShaheen Ghiassy
5,14223237
5,14223237
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jul 26 '17 at 15:15
Jorge Barraza ZJorge Barraza Z
614
614
add a comment |
add a comment |
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...
add a comment |
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...
add a comment |
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...
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...
answered Mar 1 '18 at 12:11
CodingYourLifeCodingYourLife
1,33831632
1,33831632
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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