How do you integrate Spring Boot with a NoSQL database like MongoDB?
Answer:
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.