By default, SpringData’s MappingMongoConverter add an extra “_class” column for every object saved in MongoDB. For example,

public class User {
 
	String username;
	String password;
 
	//...getters and setters
}

Save it

    MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");	
    User user = new User("mkyong", "password123");
    mongoOperation.save(user, "users");

Result

> db.users.find()
{ 
	"_class" : "com.mkyong.user.User", 
	"_id" : ObjectId("5050aef830041f24ff2bd16e"), 
	"password" : "new password", "username" : "mkyong" 
}

SpringData created this extra “_class” for a reason. To remove this extra “_class“, override the MappingMongoConverter, and passing a new DefaultMongoTypeMapper(null).

Here we show you how to remove the _class in annotation or XML way.

1. Annotation

@Configuration
public class SpringMongoConfig{
 
  public @Bean
  MongoDbFactory mongoDbFactory() throws Exception {
	return new SimpleMongoDbFactory(new Mongo(), "database");
  }
 
  public @Bean
  MongoTemplate mongoTemplate() throws Exception {
 
	//remove _class
	MappingMongoConverter converter = 
		new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
	converter.setTypeMapper(new DefaultMongoTypeMapper(null));
 
	MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);
 
	return mongoTemplate;
 
  }
 
}