Skip to content

  • Home
  • Core Java
    • Write Your Own Immutable Class In Java
    • Write Your Own Singleton Class In java
    • Java Concurrent Package
    • Java Stream Revisited
    • Print odd and even numbers using thread
    • SOLID principles
    • Comparable Vs Comparator
    • Sort HashMap/TreeMap based on value
    • Deep and Shallow Copy in Java with examples
    • Find the frequency of each character in a String
    • How to avoid duplicate Employee objects in HashSet ?
  • Spring
    • Loose Coupling & Dependency Injection
    • Bean Scope
    • Spring Bean Lifecycle
    • IoC Container Vs Application Context Vs Bean Factory
    • @Component Vs @Service @Repository Vs @Controller
    • How to read properties file in Spring
    • Spring AOP (Aspect Oriented Programming)
    • @Component Vs @Bean in Spring
    • Exception Handling in SpringBoot
    • XML configuration Vs Annotations configuration in Spring
    • Spring Data JPA
    • Spring Data REST
  • Spring Security
    • Spring Security with Form, Basic and JWT
    • Security Configuration in Spring Boot Apps
    • Security Protocols & Frameworks
    • Okta OAuth 2.0 SSO with Springboot
    • Spring Boot 2.x Security using Username Password
    • Spring Boot 2.x Security using JWT
    • Spring Boot 3.x Security using Username Password
    • Spring Boot 3.x Security using JWT
  • Microservices
    • Spring Cloud Config (Server & Client)
    • Spring Boot Microservices Tutorial (Part 1 of 2)
    • Spring Boot Microservices Tutorial (Part 2 of 2)
    • Circuit Breaker – Resilience4j
    • The Twelve-Factor App Principles
  • Event Driven Microservices
    • What is Event Driven Microservice ?
    • What is Saga Design Pattern ?
    • What is CQRS Design Pattern ?
  • Spring AI
    • ChatGPT API + SpringBoot Integration
  • Hibernate & JPA
    • JPA vs JDBC
    • CRUD Example Using Spring Boot JPA + H2 + Gradle
    • MongoDB Atlas With Spring Boot Example
    • Transaction Management
    • Relationships in JPA & Hibernate
    • Hibernate First & Second Level Cache
    • Spring Boot Flyway Postgres
  • DevOps
    • What is Devops ?
    • Docker
    • Kubernetes (K8S)
    • Jenkins
    • Infrastructure As Code
  • Functional Programming
    • Functional Programming Vs Structured Programming
    • Java 8 Programs For Interview
    • Predicate, Function, Consumer and Supplier in Java 8
    • Sort a List having Employee objects using Java 8
    • Find Employee from List using Java 8
  • AWS
    • AWS S3
    • AWS EC2
    • EC2 Solutions Architecting
    • How to create an EC2 instance ?
    • How to connect to AWS EC2 instance ?
    • Deploy application to AWS
    • AWS Lambda Java Tutorial
    • Spring Cloud Functions
    • How to Start/Stop AWS ECS automatically using Java Spring?
    • Container Solution in AWS
    • AWS SQS, SNS, MQ and Kinesis
    • Databases in AWS
    • AWS VPC: Peering, Endpoint, VPN, Gateways- Internet, NAT, DX
    • Machine Learning in AWS
    • Storage Solutions in AWS
    • AWS ASG (Auto Scaling Group)
  • AWS Certifications
    • SAA-C03
      • Design Cost-Optimized Architectures
    • AWS Certified Solution Architect-Associate
      • Question 1
  • Kafka
    • Apache Kafka
    • Kafka Producer & Consumer Example Using Spring boot & Conduktor
  • Angular
    • Angular Tutorial – Part 1
    • Angular Tutorial – Part 2
  • Miscellaneous
    • How to add a project to Git/GitHub/GitLab
    • How to Clone a project from Git/GitLab using Git Bash
    • How to query Oracle tables based on some date ?
    • How to highlight text in WordPress ?
    • How to add Page Jumps in WordPress page ?
  • Interview Preparation
    • Core java interview questions
    • Java Threads Interview Questions
  • Contact Me
  • Toggle search form

MongoDB Atlas With Spring Boot Example

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:

  1. Spring Web
  2. Lombok
  3. 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:

Repository Hierarchy

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:heapsteepofficial@heapsteepmongodbcluster.alzsrfs.mongodb.net/?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

Copyright © 2025 .

Powered by PressBook Blog WordPress theme