Tuesday, January 10, 2017

Remove _class from Mongo documents - Spring Data MongoDB

Spring Data MongoDB adds _class in the mongo documents to handle polymorphic behavior of java inheritance. If you want to remove _class just drop following Config class in your code.


package com.waseem.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

@Autowired MongoDbFactory mongoDbFactory;
@Autowired MongoMappingContext mongoMappingContext;
@Bean
public MappingMongoConverter mappingMongoConverter() {

DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));

return converter;
}
}

8 comments:

  1. WOW! Thank you so much! I was about to give up getting this to work - nothing worked, I could not get rid of those _class columns, and it was really important because I don't need them in the current project but they would take up an awful lot of extra DB space - it's about storing a huge load of annotations (very simple documents).

    I switched from using Morphia to Spring mongo data in the process, and using your workaround I was finally able to make it work. Thanks again!!

    ReplyDelete
  2. Thanks for the great solution!

    ReplyDelete
  3. How does un-marshalling work after removing _class? Specially, in case of inheritance.

    ReplyDelete
  4. In AppMongoConfig, MongoDbFactory is deprecated. use MongoDatabaseFactory instead.

    ReplyDelete
  5. Borgata Hotel Casino & Spa - Hotels - JM Hub
    Discover the Borgata Hotel Casino & Spa, Atlantic City's 이천 출장안마 premier 하남 출장마사지 Integrated Gaming 강릉 출장마사지 Resort. Modern rooms have spacious 안동 출장마사지 living spaces and suites with floor-to-ceiling 대전광역 출장마사지

    ReplyDelete