Announcement Announcement Module
No announcement yet.
Using enums as key to maps in Mongo DB Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Using enums as key to maps in Mongo DB

    I run into an issue when using enums as map key in mongo db

    The driver failed to convert my bean to DBObject because he considered the key as not immutable
    the reason is that spring driver uses the java isEnum() function to test if my class is an enum while the actual implementation of isEnum checks if this.getSuperclass() == java.lang.Enum.class;

    this is true as long as I dont have abstarcat method in my enum (implemented by each instance) becasue when I have abstract method myt enum instances are not direct decendent of Enum

    my question is - is there a way to override it - either by changing the driver to check only the modifier ((this.getModifiers() & ENUM)) or alternatively by tagging my class as legitimate key for a map by adding an annotaion.

  • #2
    Are you trying to do that through Spring Data? We're transforming map keys into Strings before passing them to MongoDB and read them back in based on the generics information of the field. So you shouldn't face this issue when using MongoTemplate. I usually prefer Enum.class.isAssignableFrom(myClass) for the reason you mentioned.


    • #3 ption: Cannot use a complex object

      I get the following exception for the test case below: ption: Cannot use a complex object as a key value.

      public void testMongoDb() throws Exception {
                      try {
      			MongoOperations mongoOps = (MongoOperations) mongoTemplate();
      			MyUser user = new MyUser("wowee", UserType.REGULAR);
      			// save
      			mongoOps.insert(user, "users");
      			// find
      			MyUser savedUser = mongoOps.findOne(new Query(Criteria.where("name").is("wowee")), MyUser.class, "users");
      			System.out.println("savedUser : " + savedUser);
      		} catch (Exception e) {
      import java.util.HashMap;
      import java.util.Map;
      public class MyUser {
      	private String name;
      	private UserType type;
      	private Map<UserType, String> descs;
      	public MyUser() {
      	public MyUser(String name, UserType type) {
      		super(); = name;
      		this.type = type;
      		this.descs = new HashMap<>();
      		descs.put(type, type.getDesc());
      public enum UserType {
      	REGULAR() {
      		public String getDesc() {
      			return "REGULAR";
      	}, VIP() {
      		public String getDesc() {
      			return "VIP";
      	public abstract String getDesc();