EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot MongoDB
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot MongoDB

Spring Boot MongoDB

Introduction to Spring Boot MongoDB

Spring Boot MongoDB is a part of umbrella spring data project that aims to provide a familiar and consistent spring based model for new datastores. As we all know, spring boot is an auto-configured microservice-based web framework with built-in features for database access and security purposes. With the help of spring boot, users can quickly create standalone applications without any configuration changes. Moreover, MongoDB being the most popular NoSQL database as data can be stored and retrieved with ease. Hence combining MongoDB with Spring boot will result in fast and secure, reliable applications that require minimum development time.

Start with Spring Boot MongoDB

Spring boot, being a quick production-ready application, interacts with MongoDB using the MongoTemplate class and MongoRepository interface. MongoTemplate class implements a set of ready-to-use APIs and is a good choice for operations such as update and aggregations. Moreover, it offers fine control over customized queries. On the other hand, the mongoRepository interface is used for basic queries that involve the field of the document, such as data creation, document view, etc.

For defining the dependency, in the pom.xml file:

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.2.5</version>
</dependency>

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Spring boot is the application framework for Java-based web applications and is based on the MVC framework. It is built on a spring framework, usually for REST APIs and requires fewer configurations.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

It has 4 layers:

  • Presentation Layer: View part of MVC that handles the front-end UI.
  • Business Layer: Controller where business logics and validations are to be done.
  • Persistence Layer: It translates business objects to database objects.
  • Database Layer: CRUD (Create, Read, Update and Delete) operations are done here.

MongoDB handles a large amount of structured and unstructured data, making the database a choice for web applications. In addition, data in MongoDB is stored as BSON objects to make data retrieval easier.

Here we shall make use of spring initializr for quick setup of the project; we shall use two dependencies, MongoTemplate and MongoRepository, as said above.

Step 1: To create a Spring boot MongoDB project, use the URL https://start.spring.io/.

Spring Boot MongoDB 1

Step 2: Select Project as “Maven Project,” Language as “Java,” and the spring boot version required. Provide required group value, artifact value, name, and description of the project. The package name will be generated automatically based on Artifact value.

Step 3: Add “Spring Web” and “Spring Data MongoDB” dependencies to the project, and click on generate.

Spring Boot MongoDB 2

Step 4: On click of the generate button, a new project is created and downloaded automatically in a zip file.

Step 5: Unzip the project and import it as a project to Eclipse IDE or any other IDE that would work.

Step 6: As the Maven Dependencies are already set up, the user can add them manually if anything else is required.

Below is the pom.xml file that has been generated. Make sure to have a stable version of the Spring Boot Maven file.

Maven Dependencies are already setup

Let us see how to create Spring Boot MongoDB REST APIs.

Step 1: By using the Spring Data MongoDB repository, we shall get access to data. Define Repository Interface first.

Step 2: Make a connection to the local instance of MongoDB, using the below syntax. Values change based on the users DB credentials.

#Local MongoDB config
spring.data.mongodb.authentication-database=sampleadmin
spring.data.mongodb.username=sample123
spring.data.mongodb.password=sample@123
spring.data.mongodb.database=sample_userDB
spring.data.mongodb.port=202107
spring.data.mongodb.host=localhost

# App
config server.port=8080
spring.application.name=SpringBootMongoDB
server.context-path=/user

The app runs on 8080 port.

Step 3: Defining APIs.

To get all users from MongoDB.

@RequestMapping(value = "", method = RequestMethod.GET)
public List<User_sample> getUsers() {
LOG.info("To get all users: ");
return userRepository.findAll();
}

Step 4: Add user.

@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public User_sample addUsers(@RequestBody User_sample user)
{
LOG.info("Adding a user."); return userRepository.save(user);
}

Step 5: Likewise, we have for deleting user, getting details of a particular user, etc.

Spring Boot MongoDB Model Class

  • It is a POJO-centric model to interact with MongoDB collection and have a Repository style data access layer.
  • Spring config supports Java-based @Configuration class or XML namespace for replica sets and Mongo driver instance.
  • MongoTemplate is a helper class which increases productivity by performing common Mongo operations that include integrated object mapping between POJOs and documents.
  • Annotation-based mapping of metadata but is also extensible in supporting other metadata formats.
  • Map Reduce integration and CDI support is given for repositories.
  • Low-level mapping of MongoReader/ MongoWriter instance.

Conclusion

With this, we shall conclude the topic “Spring Boot MongoDB.” We have seen what Spring Boot MongoDB is all about and what is the use of MongoDB. We have also seen how Spring boot acts like an easy framework in building the Java Application along with integration with the MongoDB database. We have seen how dependency can be added to the pom.xml file. Using spring initializr, we have created a Spring application and integrated the required MongoDB dependencies in the initializr itself. We have also seen steps to implement the REST API methods with Spring boot applications.

Recommended Articles

This is a guide to Spring Boot MongoDB. Here we discuss the introduction, start with spring boot MongoDB and model class. You may also have a look at the following articles to learn more –

  1. Maven Repository Spring
  2. Spring Boot DevTools
  3. Spring AOP
  4. Spring Cloud Components
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more