How To Configure MongoDB in Spring Boot
- Make sure that we have Spring Data MongoDB dependency added in pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2. Add MongoDB data source details in a property file. For example, add the below entries in application.properties file.
spring.data.mongodb.uri=mongodb://localhost:27017/test
Where 27017 is the port number of mongo server to connect and test is the database to be connected.
In a production environment with varying access-roles and credentials, you might come across with below properties.
spring.data.mongodb.authentication-database=userroledb spring.data.mongodb.database=database spring.data.mongodb.password=password
3. Make sure that data models are mapped properly with respective MongoDB collections. Especially when your Java class that represents the model have different name compared to the referred collection. You have no option but to use @Document annotation with collection names passed in above mentioned scenario.
@Document(collection="restaurants")
public class Restaurant {
@Id
private ObjectId id;
private Address address;
}