I have a C# class with some fields and some of them are null. Those that are null I do not want to be inserted into db with null value. I do not want them inserted into db a
Ensure you are registering the new convention pack early enough. If any classes have already been mapped before you register the new convention pack they won't be updated.
Here's my test code:
public class C
{
public int Id { get; set; }
public string S { get; set; }
}
public static class Program
{
public static void Main(string[] args)
{
ConventionRegistry.Register(
"Ignore null values",
new ConventionPack
{
new IgnoreIfNullConvention(true)
},
t => true);
var client = new MongoClient("mongodb://localhost");
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<C>("test");
collection.Drop();
collection.Insert(new C { Id = 1, S = null });
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
}
The following document was inserted into the database:
db.test.find()
{ "_id" : 1 }
Source: https://groups.google.com/forum/#!topic/mongodb-user/7-NFXBNeEXs
Using the aptly named [BsonIgnoreIfNull] attribute:
class User
{
public string FirstName;
public string LastName;
[BsonIgnoreIfNull]
public string MidName;
}