Home > front end >  Spring where I should connect to my MongoDB?
Spring where I should connect to my MongoDB?

Time:07-22

I want to connect to my database (MongoDB) but I don't know what file is responsible for this.

My project structure

In which file can I stuff it?

ConnectionString connectionString = new ConnectionString("<DATABASE URL>");
MongoClientSettings settings = MongoClientSettings.builder()
        .applyConnectionString(connectionString)
        .serverApi(ServerApi.builder()
            .version(ServerApiVersion.V1)
            .build())
        .build();
MongoClient mongoClient = MongoClients.create(settings);
MongoDatabase database = mongoClient.getDatabase("test");

CodePudding user response:

First you need to install MongoDB Spring Boot dependency

Then in your application.properties you need to put MongoDB URI like that: spring.data.mongodb.uri = [URI]

On your project structure i can see UserRepository, it should look similar to this:

@Repository
public interface UserRepository extends MongoRepository<UserEntity, String> {

}

And now you can use your UserRepository everywhere just by using @Autowired UserRepository userRepository

  • Related