Get _id of an inserted document in MongoDB?

前端 未结 6 1869
渐次进展
渐次进展 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条回答
  •  Happy的楠姐
    2020-12-07 00:51

    The Insert method automatically sets the property that is declared as the BSON ID of the model.

    If declared as follows...

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

    ... then the Id field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:

    coll.Insert(obj);
    // obj.Id is now the BSON ID of the object
    

提交回复
热议问题