Skip to content

NULLs in MongoDB

By default, the C# driver’s serializer takes a null value and assigns a default, rather than just writing the word NULL in the collection when inserting.

So if you had a an object that had 50 properties, only set 1 value in it, and passed it to MongoDB, it would insert all 50 properties, which would be wasteful (depending on how you looked at it).

One can decorate the property with the [BsonIgnoreIfNull] attribute and will not write that element to the db if it’s null. However, if you don’t always want to use this property, one can set it once (and forget it) by creating a MongoDB “ConventionProfile” across the entire application. We have this setup in the Global.asax.cs so it gets created when the application is loaded:

var profile = new ConventionProfile(); 
profile.SetIgnoreIfNullConvention(new AlwaysIgnoreIfNullConvention()); 
BsonClassMap.RegisterConventions(profile, t => true);

However, even with that, it only appears that it does this only for strings that are null. If you have a property that’s Boolean, Integer, or Date, it will still write the elements to the database, setting Booleans to Falses, Integers to 0, and Dates to an ISO timestamp. It does this partly because these data types don’t implement a NULL property, so they can’t be null. To “make” them NULL, you have to use the question mark after the data type, like so:

bool? IsEnabled;
int? MagicNumber;
Date? TimeStamp;

All three are short for:

Nullable isEnabled;
Nullable MagicNumber;
Nullable TimeStamp;

Categories

Databases, MongoDB

Dan View All

Blog owner.

%d bloggers like this: