Auto default value in the C# Driver

Hey, is there a way to default to a value when a field is missing in the document itself.
So basically, I have a list of strings and this may be null for certain documents (because this field was added afterwards) and in this case I want to just default to the already assigned value, but the MongoDB Driver automatically overrides the value to null. Is there a way to achieve this?

[BsonElement("disabled_commands")] public List<string> MyList{ get; set; } = new List<string>();

With friendly regards

Hi @ZargorNET, and welcome to the forum

You can utilise SetDefaultValue() to assign a value to a field if the document does not have a value for the field (null is a value) during deserialisation.

For example if you have the following document stored in the database :

{
  "_id": ObjectId("5f583cc562d0ce4a58c7da08"),
  "Name": "X"
}

With class mapping example as below:

public class MyClass 
{
    [BsonId]
    private ObjectId Id {get; set;}
    public string Name {get; set;}
    public List<string> MyList {get; set;}
}

You can register and set a default value for deserialisation as below:

BsonClassMap.RegisterClassMap<MyClass>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(x => x.MyList).SetDefaultValue(new List<string>());
});

This should deserialise MyList value into []. For more information see also MongoDB .NET/C# Mapping Classes

Without knowing more of the context, you could also declare a constructor the class. This should help defined a default value before inserting to the database. For example:

 public class MyClass 
 {
     [BsonId]
     private ObjectId Id {get; set;}
     public string Name {get; set;}
     public List<string> MyList {get; set;}

     public MyClass () 
     {
         Name = "";
         MyList = new List<string>();
     }
}

Regards,
Wan.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.