DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Manage Hierarchical Data in MongoDB With Spring
  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • MongoDB to Couchbase for Developers, Part 1: Architecture

Trending

  • Why Your RAG Pipeline Will Fail Without an MCP Server
  • Evolving Spring Boot APIs to an Event-Driven Mesh
  • Manual Investigation: The Hidden Bottleneck in Incident Response
  • Lease Coordination Under Serializable Isolation in CockroachDB
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB With Spring Boot: A Simple CRUD

MongoDB With Spring Boot: A Simple CRUD

In this blog, we are going to explore MongoDB with Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.

By 
Upanshu Chaudhary user avatar
Upanshu Chaudhary
·
Mar. 21, 21 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
17.3K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB is an open-source non relational, document oriented database. MongoDB being document oriented means that it stores data in JSON like documents which makes it more powerful and expressive. MongoDB’s ability to scale up and down very easily is considered to be one of its advantages over its competitors. Data is stored in documents in key pair values. Another component of MongoDB is collection, which is the simple collection of documents. Collection corresponds to Table in relational databases. In this blog we are going to explore this database with Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.

Why Use MongoDB?

  1. It is document based and therefore it is more flexible where each document can have varying fields which can not be done in relational databases.
  2. It allows us to index any field in the document to improve search results.
  3. It provides us with rich and powerful query language which allows us to filter and sort using any field no matter how nested the field is.
  4. It provides us with high scalability (sharding) and high availability (replication) of data.

MongoDB With Java Spring Boot

Assuming that you have a basic understanding of MongoDB now we will now see how we can leverage MongoDB by building a small spring boot API to perform basic CRUD operations.

Prerequisites

  • You should have MongoDB installed in your local environment. To save yourself some time setting it up you can also use a MongoDB Docker image, you can see how to do it here. This application will run in the default mongo port.
  • Create a Spring Boot application with web-started and mongo dependencies. You can match your pom.xml with the one provided on the project repository.

Project Structure

Project Structure spring-mongo-crud

Model

This package will have the java object model for the document. We have created a simple Person model here with fields id and name.

The @Document annotation is used to define the name of the collection in which your document will be saved.

Java
 




x
29


 
1
@Document(collection = "Person")
2
public class Person {
3
    @Id
4
    private String id;
5
    private String name;
6

          
7
    public Person(@JsonProperty("id") String id,
8
                  @JsonProperty("name") String name) {
9
        this.id = id;
10
        this.name = name;
11
    }
12

          
13
    public String getId() {
14
        return id;
15
    }
16

          
17
    public String getName() {
18
        return name;
19
    }
20

          
21
    public void setId(String id) {
22
        this.id = id;
23
    }
24

          
25
    public void setName(String name) {
26
        this.name = name;
27
    }
28
}



DAO

DAO in our project is the data access object. It contains the implementation for the Mongo repository.

Here, we have created an Interface PersonRepository which extends the MongoRepository Interface. MongoRepository comes with basic CRUD operations for us to use out of the box. Making our task easier.

The implementation of the PersonRepository is in the PersonDao class. All these operations will be done using API.

Inserting Data (Create)

Here, insert() method will take Person object as parameter and insert the person details  into MongoDB.

Java
 




xxxxxxxxxx
1


 
1
  public Person insertPersonData(Person person) {
2
        return personRepository.insert(person);
3
}



Getting Data (Read)

Here, we have defined two methods for reading data from MongoDB. 

  • For getting all person information: getAllPersonInformation() 

It will return a collection of Person.

Java
 




xxxxxxxxxx
1


 
1
 public Collection<Person> getAllPersonInformation() {
2
        return personRepository.findAll();
3
    }



  • For getting information of a specific person: getPersonById()

This method will take id as a parameter and return the person information matching the ID.

Java
 




xxxxxxxxxx
1


 
1
 public Optional<Person> getPersonInformationById(String id) {
2

          
3
        return personRepository.findById(id);
4
    }



Updating Existing Data

Here, updatePersonUsingId() method will take the id and the person object as parameters.

Java
 




xxxxxxxxxx
1


 
1
public Person updatePersonUsingId(String id, Person person) {
2

          
3
        Optional<Person> findPersonQuery = personRepository.findById(id);
4
        Person personValues = findPersonQuery.get();
5
        personValues.setId(person.getId());
6
        personValues.setName(person.getName());
7
        return personRepository.save(personValues);
8
    }



Deleting Data

Here, the method deletePersonUsingId() will take an id as a parameter and delete the person data corresponding to the ID.

Java
 




xxxxxxxxxx
1


 
1
public void deletePersonUsingId(String id) {
2

          
3
        try {
4
            personRepository.deleteById(id);
5
        } catch (NoSuchElementException e) {
6
            e.printStackTrace();
7
        }
8
}



This is it. All these operations can be done by using the API we have given in the controller. Test this application using the Postman.

Conclusion

This is just a basic CRUD example for a quick walk through but production level code is more crisp, detailed and contains many scenarios. This example is no where near that.

The link for this project is given below and contains a docker-compose.yml with MongoDB image to help you run this example quickly!

Link to Github repository for the project is here.

Spring Framework MongoDB Spring Boot Data (computing) Relational database Document Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Manage Hierarchical Data in MongoDB With Spring
  • Java and MongoDB Integration: A CRUD Tutorial [Video Tutorial]
  • MongoDB to Couchbase for Developers, Part 1: Architecture

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook