ConventionRegistry.Register("IgnoreIfDefault",
new ConventionPack { new IgnoreIfDefaultConvention(true) },
_ => true);
var bsonDocument = anon.ToBsonDocument();
using IgnoreIfDefaultConvention can cause an unintended behavior due to the fact it affects all default values. For instance, values, as listed below, will not be saved:
int = 0
decimal = 0
bool = false
If I want to ignore only null values and Empty Arrays what is the best approach?
I didn't use it my own, but I think the answer is this convention: IgnoreIfNullConvention
. Also you may configure a particular convention for a particular field:
BsonClassMap.RegisterClassMap<test>(c => c.MapField(e => e.A).SetIgnoreIfNull(ignoreIfNull: true));
or use this attribute BsonIgnoreIfNullAttribute
UPDATE: If you need more complicated convention, you can always implement a custom one: https://mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/mapping/conventions/