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.
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.
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.
Enumerations, also known as enums, are not supported natively in the Java SDK.
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.
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 conventions var pack = new ConventionPack { new EnumRepresentationConvention(BsonType.String) }; ConventionRegistry.Register("EnumStringConvention", pack, t => true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With