mongoDB with SpringBooot- A simple CRUD

Knoldus Blog Audio
Reading Time: 3 minutes

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 simply 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

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.

@Document(collection = "Person")
public class Person {
    @Id
    private String id;
    private String name;

    public Person(@JsonProperty("id") String id,
                  @JsonProperty("name") String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

}

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 the Data(Create)

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

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

Getting the 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.

  public Collection<Person> getAllPersonInformation() {
        return personRepository.findAll();
    }
  • for getting information of specific: getPersonById()

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

  public Optional<Person> getPersonInformationById(String id) {

        return personRepository.findById(id);
    }

Updating the existing data

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

public Person updatePersonUsingId(String id, Person person) {

        Optional<Person> findPersonQuery = personRepository.findById(id);
        Person personValues = findPersonQuery.get();
        personValues.setId(person.getId());
        personValues.setName(person.getName());
        return personRepository.save(personValues);
    }

Deleting data

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

public void deletePersonUsingId(String id) {

        try {
            personRepository.deleteById(id);
        } catch (NoSuchElementException e) {
            e.printStackTrace();
        }
    }

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.

Link to github repository for the project is here.

Checkout our other blogs on java and mongo on Knoldus blogs.

This image has an empty alt attribute; its file name is footer-2.jpg

Leave a Reply