Get _id of an inserted document in MongoDB?

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

Leave a Comment