How do you integrate Spring Boot with a NoSQL database like MongoDB?

How do you integrate Spring Boot with a NoSQL database like MongoDB?

A) By using the spring-boot-starter-data-mongodb dependency
B) By manually configuring the MongoDB client in the application
C) By using the spring-boot-starter-nosql dependency
D) By using the @NoSql annotation

Answer:

A) By using the spring-boot-starter-data-mongodb dependency

Explanation:

To integrate Spring Boot with a NoSQL database like MongoDB, you can use the spring-boot-starter-data-mongodb dependency. This starter provides all the necessary dependencies and configuration to connect and interact with a MongoDB database.

First, add the spring-boot-starter-data-mongodb dependency to your project:


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Then, you can define a repository interface for your MongoDB collections by extending MongoRepository:


import org.springframework.data.mongodb.repository.MongoRepository;

public interface MyRepository extends MongoRepository<MyEntity, String> {
    // Custom query methods can be added here
}

Spring Boot will automatically configure the MongoDB connection based on the properties you provide in application.properties or application.yml:


spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase

With these configurations, your Spring Boot application can interact with MongoDB using the familiar Spring Data repositories, making it easier to perform CRUD operations and other database interactions with minimal setup.

Reference links:

Spring Boot Tutorialhttps://www.javaguides.net/p/spring-boot-mongodb-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top