Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Enums as strings in MongoDB

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.

like image 276
Kostassoid Avatar asked Aug 09 '11 12:08

Kostassoid


People also ask

Can enums be strings?

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.

How is enum stored in Mongodb?

Steps: Create and register a codec provider with Mongo Code Registry which Mongo uses to determine which Enum decoder to use a Java Enum value. Create and register Enum decoder for ProcessType. Create and register Enum with DB.

Does Mongodb support enum?

Enumerations, also known as enums, are not supported natively in the Java SDK.

Can enums contain numbers?

Numeric EnumNumeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


2 Answers

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; } } 
like image 50
John Gietzen Avatar answered Sep 20 '22 16:09

John Gietzen


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 conventions var pack = new ConventionPack {     new EnumRepresentationConvention(BsonType.String) };  ConventionRegistry.Register("EnumStringConvention", pack, t => true); 
like image 28
Ricardo Rodriguez Avatar answered Sep 21 '22 16:09

Ricardo Rodriguez