Mongodb C# 驱动程序忽略 Null 和空列表 (ToBsonDocument)

Mongodb C# driver ignore Null and Empty Lists (ToBsonDocument)

ConventionRegistry.Register("IgnoreIfDefault", 
                            new ConventionPack { new IgnoreIfDefaultConvention(true) }, 
                            _ => true);

var bsonDocument = anon.ToBsonDocument();

使用 IgnoreIfDefaultConvention 可能会导致意外行为,因为它会影响所有默认值。例如,不会保存如下所列的值:

int = 0
decimal = 0
bool = false

如果我只想忽略 空值和空数组什么是最好的方法?

我自己没有使用它,但我认为答案是这个约定:IgnoreIfNullConvention。您也可以为特定字段配置特定约定:

BsonClassMap.RegisterClassMap<test>(c => c.MapField(e => e.A).SetIgnoreIfNull(ignoreIfNull: true));

或使用此属性BsonIgnoreIfNullAttribute

更新: 如果你需要更复杂的约定,你总是可以实现一个自定义的:https://mongodb.github.io/mongo-csharp-driver/2.12/reference/bson/mapping/conventions/