connecting to mongo database in spring boot

To connect to a MongoDB database in a Spring Boot application, you can follow these steps:

  1. Add the MongoDB dependency in your pom.xml file:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  1. Configure the MongoDB connection in application.properties:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase
  1. Create a MongoDB configuration class:
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfig {
}
  1. Create a model class representing a document in the MongoDB collection:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "mycollection")
public class MyDocument {
    @Id
    private String id;
    private String name;
    // ... other fields, getters, and setters
}
  1. Create a repository interface for interacting with the MongoDB collection:
import org.springframework.data.mongodb.repository.MongoRepository;

public interface MyDocumentRepository extends MongoRepository<MyDocument, String> {
    // ... custom query methods if needed
}
  1. Inject the repository in your service or controller classes and use it to perform database operations.

These steps will enable you to connect to a MongoDB database in a Spring Boot application and perform CRUD operations using Spring Data MongoDB.