Skip to main content

Mongo DB Conditional Serialization


Mongo DB - Conditional Serialization


Sometimes, the documents retrieved from the database should be serialized differently for different conditions. We can make use of the below technique to do that,


public class Company {

    public ObjectId Id { get; set; }

    [BsonDateTimeOptions(DateOnly = true)]

    public DateTime JoiningDate { get; set; }


    public bool ShouldSerializeJoiningDate() {

        return JoiningDate > new DateTime(1900, 1, 1);

    }

}


For more information on conditional serialization, refer the Mongo DB documentation below

https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/

Comments