using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; namespace TestNeverSerializeDefaultValueConvention { public class C { public int Id; public Guid G; } public class EmptyGuidDefaultValueConvention : IDefaultValueConvention { public object GetDefaultValue( MemberInfo memberInfo ) { var type = (memberInfo.MemberType == MemberTypes.Field) ? ((FieldInfo) memberInfo).FieldType : ((PropertyInfo) memberInfo).PropertyType; if (type == typeof(Guid)) { return Guid.Empty; } else { return null; } } } public static class Program { public static void Main(string[] args) { try { InitializeSerialization(); var server = MongoServer.Create("mongodb://localhost/?safe=true"); var database = server["test"]; var collection = database["test"]; collection.Drop(); collection.Insert(new C { Id = 1 }); foreach (var document in collection.FindAll()) { Console.WriteLine(document.ToJson()); // document should NOT have a "G" element but does } } catch (Exception ex) { Console.WriteLine("Unhandled exception:"); Console.WriteLine(ex); } Console.WriteLine("Press Enter to continue"); Console.ReadLine(); } private static void InitializeSerialization() { var conventions = new ConventionProfile(); conventions.SetDefaultValueConvention(new EmptyGuidDefaultValueConvention()); conventions.SetSerializeDefaultValueConvention(new NeverSerializeDefaultValueConvention()); BsonClassMap.RegisterConventions(conventions, type => type.FullName.StartsWith("TestNeverSerializeDefaultValueConvention.")); } } }