Spring Boot & MongoDB how to remove the '_class' column?

Dave's answer is correct. However, we generally recommend not do this (that's why it's enabled by default in the first place) as you effectively throw away to persist type hierarchies or even a simple property set to e.g. Object. Assume the following type:

@Document
class MyDocument {

  private Object object;
}

If you now set object to a value, it will be happily persisted but there's no way you can read the value back into it's original type.


I think you need to create a @Bean of type MongoTemplate and set the type converter explicitly. Details (non-Boot but just extract the template config): http://www.mkyong.com/mongodb/spring-data-mongodb-remove-_class-column/


Here is a slightly simpler approach:

@Configuration
public class MongoDBConfig implements InitializingBean {

    @Autowired
    @Lazy
    private MappingMongoConverter mappingMongoConverter;

    @Override
    public void afterPropertiesSet() throws Exception {
        mappingMongoConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    }
}

A more up to date answer to that question, working with embedded mongo db for test cases: I quote from http://mwakram.blogspot.fr/2017/01/remove-class-from-mongo-documents.html

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;
 }
}