Storing Enums as strings in MongoDB

Kostassoid picture Kostassoid · Aug 9, 2011 · Viewed 31.5k times · Source

Is there a way to store Enums as string names rather than ordinal values?

Example:

Imagine I've got this enum:

public enum Gender
{
    Female,
    Male
}

Now if some imaginary User exists with

...
Gender gender = Gender.Male;
...

it'll be stored in MongoDb database as { ... "Gender" : 1 ... }

but i'd prefer something like this { ... "Gender" : "Male" ... }

Is this possible? Custom mapping, reflection tricks, whatever.

My context: I use strongly typed collections over POCO (well, I mark ARs and use polymorphism occasionally). I've got a thin data access abstraction layer in a form of Unit Of Work. So I'm not serializing/deserializing each object but I can (and do) define some ClassMaps. I use official MongoDb driver + fluent-mongodb.

Answer

John Gietzen picture John Gietzen · Jul 17, 2012
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; }
}