4

I have a problem. After having created a Spring Boot project with Eclipse and configuring the application.properties file, my collections are not created, whereas after execution, the Eclipse console signals that the connection to MongoDB has been carried out normally. I don't understand what's going on. With MySQL we had the tables created so I expected the creation of the collections, but nothing.

Summary, I don't see my collection (class annoted @Document) in MongoDB after deployment.

3
  • How do you check the collection data in your mongo database? Additionally, you should share some classes of your your for we can check of you has configured it correctly Commented Apr 16, 2020 at 6:00
  • 1
    Did you add the spring-boot-starter-data-mongodb dependency? If yes, did you add a repository für the @Document annotated class? Commented Apr 16, 2020 at 9:52
  • In MongoDB a collection is created (1) when a document is inserted into a new (non-existing) collection, or (2) you have to create the collection explicitly. Are there any existing collections in the database you are trying to read from the Spring application? Commented Apr 16, 2020 at 9:52

2 Answers 2

5

You could do this in two ways through Spring. I tested the instructions below in Spring 2.1.7.

With just a @Document class, Spring will not create a collection in Mongo. It will however create a collection if you do the following:

  1. You have a field you want to index in the collection, and you annotate it as such in the Java class. E.g.

    @Indexed(unique = true)
    private String indexedData;
    
  2. Create a repository for the collection:

    public interface MyClassRepository extends MongoRepository<MyClass, String> {
    }
    

If you don't need/want an index, the second way of doing this would be to add some code that runs at startup, adds a dummy value in the collection and deletes it again.

@Configuration
public class LoadDatabase {
    @Bean
    CommandLineRunner initDb(MyClassRepository repository) {
        // create an instance of your @Document annotated class
        MyClass myDocument = new MyClass();
        
        myDocument = repository.insert(myDocument);
        repository.delete(myDocument);
    }
}

Make sure your document class has a field of the correct type (String by default), annotated with @Id, to map Mongo's _id field.

Sign up to request clarification or add additional context in comments.

1 Comment

This should be accepted answer.
2

New collection won't be created until you insert at least one document. Refer the document Create Collection

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.