Storing Enums as strings in MongoDB Storing Enums as strings in MongoDB mongodb mongodb

Storing Enums as strings in MongoDB


using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;using Newtonsoft.Json;using Newtonsoft.Json.Converters;public class Person{    [JsonConverter(typeof(StringEnumConverter))]  // JSON.Net    [BsonRepresentation(BsonType.String)]         // Mongo    public Gender Gender { get; set; }}


The MongoDB .NET Driver lets you apply conventions to determine how certain mappings between CLR types and database elements are handled.

If you want this to apply to all your enums, you only have to set up conventions once per AppDomain (usually when starting your application), as opposed to adding attributes to all your types or manually map every type:

// Set up MongoDB conventionsvar pack = new ConventionPack{    new EnumRepresentationConvention(BsonType.String)};ConventionRegistry.Register("EnumStringConvention", pack, t => true);


You can customize the class map for the class that contains the enum and specify that the member be represented by a string. This will handle both the serialization and deserialization of the enum.

if (!MongoDB.Bson.Serialization.BsonClassMap.IsClassMapRegistered(typeof(Person)))      {        MongoDB.Bson.Serialization.BsonClassMap.RegisterClassMap<Person>(cm =>         {           cm.AutoMap();           cm.GetMemberMap(c => c.Gender).SetRepresentation(BsonType.String);         });      }

I am still looking for a way to specify that enums be globally represented as strings, but this is the method that I am currently using.