Do not insert a field if it is empty or empty

I have a C # class with some fields, and some of them are null. Those that are null, I don't want to embed in db with a null value. I do not want them inserted in db. How do I achieve this?

class User { public string FirstName; public string LastName; public string MidName; } 

Not every user has the name MidName, but Mongo is inserted into db with a null value in the MidName field.

+8
source share
2 answers

Using the aptly named [BsonIgnoreIfNull] :

 class User { public string FirstName; public string LastName; [BsonIgnoreIfNull] public string MidName; } 
+9
source

Make sure you register the new convention package early enough. If any classes have already been mapped before you register a new agreement package, they will not be updated.

Here is 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 has been inserted into the database:

db.test.find ()

 { "_id" : 1 } 

Source: https://groups.google.com/forum/#!topic/mongodb-user/7-NFXBNeEXs

+7
source

Source: https://habr.com/ru/post/1210717/


All Articles