Get _id of an inserted document in MongoDB?

前端 未结 6 1867
渐次进展
渐次进展 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条回答
  •  萌比男神i
    2020-12-07 00:47

    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.

提交回复
热议问题