MongoDB .NET not generating _id on upsert MongoDB .NET not generating _id on upsert mongodb mongodb

MongoDB .NET not generating _id on upsert


And of course I find the answer immediately after posting the question. From this answer, the solution is to add a [BsonIgnoreIfDefault] attribute to the ID. In the example from the question it would be:

public class MongoObject{    [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]    [BsonRepresentation(BsonType.ObjectId)]    [BsonIgnoreIfDefault]    // <--- this is what was missing    public string MongoID { get; set; }    public int Index { get; set; }}