How to ignore null values globally by calling obj.ToBsonDocument() using MongoDB C# driver?
You can apply the effects of most attributes to all properties while serializing by registering convention packs.
Below the IgnoreIfDefaultConvention
is registered, implicitly applying the [IgnoreIfDefault]
attribute to all properties while serializing and deserializing.
var anon = new
{
Foo = "bar",
Baz = (string)null,
};
ConventionRegistry.Register("IgnoreIfDefault",
new ConventionPack { new IgnoreIfDefaultConvention(true) },
t => true);
var bsonDocument = anon.ToBsonDocument();
This will yield a document only containing the Foo
key.
When desired, you can also Remove()
this convention pack by name after serialization.
You can also apply the [BsonIgnoreIfNull]
attribute from the MongoDB.Bson.Serialization.Attributes
namespace to a class field if you don't what that field with a null value to appear in the BSON Document.
public class Person
{
public string Name { get; set; }
[BsonIgnoreIfNull]
public List<string> Children { get; set; }
}