azobs
azobs

Reputation: 51

Spring Boot + MongoDB+create collection

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.

Upvotes: 4

Views: 10554

Answers (2)

devil0150
devil0150

Reputation: 1469

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.

Upvotes: 5

varman
varman

Reputation: 8894

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

Upvotes: 2

Related Questions