Like the other answers here, identifiers are assigned on the client side. Something you can do is create a default convention that generates a new identifier during insertion, if it is not already set.
public class DefaultValueConvention : MongoDB.Bson.Serialization.Conventions.IDefaultValueConvention { public object GetDefaultValue(MemberInfo memberInfo) { var type = memberInfo.MemberType == MemberTypes.Property ? ((PropertyInfo) memberInfo).PropertyType : ((FieldInfo) memberInfo).FieldType; if (type.IsSubclassOf(typeof(ObjectId))) return ObjectId.GenerateNewId(); else return null; } }
And configure the driver to use this convention:
var profile = new ConventionProfile(); profile.SetDefaultValueConvention(new DefaultValueConvention()); BsonClassMap.RegisterConventions(profile, x => x.FullName.StartsWith("ConsoleApplication"));
So now you can create an object and save it in two lines:
var animal = new Animal {Name = "Monkey", PercentDeviationFromHumans = 2.01}; db["animals"].Save(animal);
Actually, with the latest driver, you donβt even need to set a standard default agreement, it already has this OOTB behavior. Despite this, agreements in mangoes are not used enough.
source share