say I have a product listing. When I add a new product I save it using something like
var doc=products.Insert(p);
The pro
If you know the type of ID you can do something like this:
public static TId GetId(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();
Still you should prefere have a dedicated property as in the chosen answer...