Spring Data MongoDB provides repository and data-access abstractions for MongoDB in Spring applications. It is especially useful when replacing relational persistence with a document-oriented backend that supports horizontal scaling and evolving schemas. section 2.1
A disciplined migration checks more than the repository interface:
- Replace relational repository dependencies with MongoRepository, adapt configuration, and document the requirement for a running MongoDB instance. section 2.10.1
- Replace SQL-based prepopulation with a DataInitializer and update repository tests to exercise MongoDB rather than assuming the migration is correct. section 2.10.1
- Expect better automation when the application consistently uses Spring; mixed JBoss and Spring code makes framework context harder to infer. section 2.10.1
import org.spring.as.quickstarts.kitchensink.model.Member;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MemberRepository extends MongoRepository<Member, String> {
Member findByEmail(String email);
@Query(value = "{}", sort = "{ 'name' : 1 }")
List<Member> findAllOrderedByName();
}
DataInitializer.java
@Configuration
public class DataInitializer {
@Autowired
private MemberRepository memberRepository;
@Bean
public CommandLineRunner initData(MongoTemplate mongoTemplate) {
return args -> {
// Drop existing collection
mongoTemplate.dropCollection("members");
// Load initial data
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ClassPathResource resource = new ClassPathResource("data/members.json");
List<Member> members = mapper.readValue(resource.getInputStream(), new TypeReference<List<Member>>() {});
memberRepository.saveAll(members);
};
}
} Inspect a concrete MemberRepository using MongoRepository, a derived email lookup, sorted retrieval, and a MongoTemplate-backed initializer. section 2.10.1
Repository migration
A migration prompt can request replacing the relational database with MongoDB. A resulting MemberRepository extends MongoRepository<Member, String>, while initialization drops the members collection and loads initial data through MongoTemplate. section 2.10.1


