Search code examples
mongodbspring-bootspring-data-mongodbmongotemplateaws-documentdb

SpringBoot: Create document in mongodb on startup if not exists


I have a small service on SpringBoot and Mongodb as a DB. I need to be able create a small collection with one document ( very basic: id, name, status) on startup. An analog of sql create table if not exists, but for mongo. How do I do that? I tried to initialize values in the document attributes, but it didn't help. Currently, collection and the document appear only if I use API to add it.


Solution

  • You may want to use something like ApplicationRunner or CommandLineRunner which can be defined as a bean.

    Example:

    @SpringBootApplication
    public class MyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MyApplication .class, args);
        }
    
        @Bean
        public CommandLineRunner initialize(MyRepository myRepository) {
    
            return args -> {
                // Insert elements into myRepository 
            };
        }
    }
    

    Both CommandLineRunner and ApplicationRunner are functional interfaces, so we can use a lambda for them. Spring Boot will execute them at the startup of the application.