Get _id of an inserted document in MongoDB?

前端 未结 6 1856
渐次进展
渐次进展 2020-12-07 00:34

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

6条回答
  •  执笔经年
    2020-12-07 00:47

    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...

提交回复
热议问题