What is MongoDB:
MongoDB is a No SQL database. Unlikely in SQL database which stores data in tables, columns and rows, it stores data in the form of Document and Collection. A document is like a JSON object having key-value pair data.
A document example:
{ "bookName": "Java Complete Reference", "price": 250, "author": "James Gosling", "publication": "OReily" }
A collection is a group of similar kind of documents. In the below diagram Books is a Collection which stores Book documents only.
What is MongoDB Atlas:
MongoDB Atlas is a Database As A Service tool, where your database will not be deployed in your local system, rather on to a cloud of your choice- AWS, Azure or GCP.
Steps for creating a account in MongoDB Atlas:
Its a simple and free process, go to this url- MongoDB Atlas. Enter the asked details and follow the process.
Once you have created the account you may see the page something like below:
Click “Build a Database”.
Then you have to choose the “Free” tier along with the cloud provider and the region. Give a name to the cluster and hit “Create”.
Then you have to create the Security Quickstart. For that add a new “Username” and “Password“. Then choose “My Local Environment” since you have to connect from your laptop. There you need to add your local IP address and hit “Finish and Close”.
Now your MongoDB Atlas cluster is ready to be used.
Lets now build our Spring Boot application in the next section.
Spring Boot App to Connect to MongoDB:
Create an Spring Boot application by adding below dependencies:
- Spring Web
- Lombok
- Spring Data MongoDB
Hope you had the lombok setup for your IDE, if not you can refer here.
Write the Entity class Book.java. Add the @Document annotation and as best practice better to add the name of the collection:
@Document(collection="Book_collection") @Data @AllArgsConstructor @NoArgsConstructor public class Book { @Id private String id; private String bookName; private Double price; private String author; private String publication; }
Then write a repository class BookRepository.java by extending from MongoRepository or CrudRepository:
//public interface BookRepository extends MongoRepository<Book,String>{ public interface BookRepository extends CrudRepository<Book,String>{ }
For your reference, below is the hierarchy of the important Spring Data JPA repositories:
Then write the service class BookService.java. In this we need to set the Id, as in MongoDB it will not be auto generated. And for that we had taken help of randomUUID which will generate some string like this: ba3e191e-acb0-4b57-b96e-7116698c169a and then we had split it for “–” to get value ba3e191e.
@Service public class BookService { @Autowired BookRepository bookRepository; public Book addBook(Book book) { book.setId(UUID.randomUUID().toString().split("-")[0]); return bookRepository.save(book); } }
Then add the controller class- BookController.java :
@RestController @RequestMapping("/books") public class BookController { @Autowired BookService bookService; @PostMapping("/addbook") @ResponseStatus(HttpStatus.CREATED) public Book addBook(@RequestBody Book book){ return bookService.addBook(book); } }
Now we need to add the MongoDB uri to application.yml file. You can give any name to the database:
spring: data: mongodb: uri: mongodb+srv://heapsteepofficial:[email protected]/?retryWrites=true&w=majority database: Book_DB
You can get the MongoDB uri from below location:
Click Connect:
Finally run the Spring Boot application and you can see the server is getting started. And before that, one can see its getting connected to MongoDB as well:
Now lets do a POST call to the below endpoint and JSON parameters:
http://localhost:8080/books/addbook
{ "bookName": "Java Complete Reference", "price": 250, "author": "James Gosling", "publication": "OReily" }
And one can see the output like below:
If you go and check the console of MongoDB Atlas, you can see a database and a collection is created, and its populated with a document. We have not created any of those before hand :
Source code of this project:
https://github.com/heapsteep/mongodb-atlas