Spring Boot and NoSQL Database MongoDB
This post briefly documents the usage of MongoDB, a general purpose, document-based, distributed database with Spring Boot.
Minimum Software Requirements
MongoDB Installation
On Windows platform, create a folder titled data inside another folder named db, in C: drive. (C:\data\db)
For other platforms, check the installation guide by MongoDB.
Start the mongod server from the \bin folder of the MongoDB installation location (C:\Program Files\MongoDB\Server\4.0\bin).
Sample Project
Spring Boot MongoDB is the sample CRUD Spring Boot web application i've used to illustrate the usage of MongoDB.
Navigate to http://localhost:8080/ to discover the application URLs.
Noticed an issue with this Sample Project? Open an issue or a PR on GitHub!
ER Diagram
Sample Valid JSON Request Body for PUT and POST requests.
{
"name": "John Doe",
"email": "example@domain.com",
"department": {
"departmentName": "computer science",
"location": "Dystopia"
},
"subjects": [
{
"subjectName": "Java",
"marksObtained": 80
},
{
"subjectName": "Chemistry",
"marksObtained": 90
}
],
"demographics": {
"country": "usa",
"age": 50
},
"hobbies": [
{
"hobbyName": "music",
"interestLevel": 4
},
{
"hobbyName": "sports",
"interestLevel": 3
}
]
}
Dependencies
This implementation has one dependency, spring-boot-starter-data-mongodb. The maven/gradle dependencies of the same is mentioned below.
MongoDB
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
or
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
Basic Usage
Application Configuration
In the application.properties file configure the following properties.
Data Properties
# Mongo server host. Cannot be set with URI.
spring.data.mongodb.host=localhost
# Mongo server port. Cannot be set with URI.
spring.data.mongodb.port=27017
# Database name.
spring.data.mongodb.database=spring
Application Execution
Build and run the application via an IDE or by issuing the following command:
mvnw spring-boot:run