In this article, we’ll explore MongoDB using Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.

MongoDB is an open source, non-relational, document-oriented database. MongoDB’s document-orientation means that it stores data in document-like JSON, which makes it more powerful and expressive. MongoDB’s ability to easily scale and scale back is cited as one of its advantages over its competitors. The data is stored in the document as key pair values. Another component of MongoDB is collections, which are simple collections of documents. Collection corresponds to a Table in a relational database. In this blog post, we’ll explore this database using Java Spring Boot. We will create a simple CRUD API to interact with our Mongo database.

Why use MongoDB?

It is document-based, so it is more flexible in that each document can have different fields, which is not possible in a relational database. It allows us to index any field in a document to improve search results. It gives us a rich and powerful query language that allows us to filter and sort with any field, no matter how nested that field is. It provides us with high scalability (sharding) and high availability (replication) of the data.

MongoDB and Java Spring Boot

Assuming that you now have a basic understanding of MongoDB, we will now look at how to leverage MongoDB to perform basic CRUD operations by building a small Spring Boot API.

A prerequisite for

  • You should have MongoDB installed in your local environment. To save setup time, you can also use the MongoDB Docker image, which you can see how to do here. This application will run on the default Mongo port.
  • Create the Spring Boot application using the Web Boot and Mongo dependencies. You can match pom.xml with the pom.xml provided in the project repository.

The project structure

model

The package will have a Java object model for the document. Here we create a simple Person model that contains the field ID and name.

The @Document annotation is used to define the name of the collection in which the 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

The DAO in our project is a data access object. It contains the implementation of the Mongo repository.

Here, we create a PersonRepository interface that extends the MongoRepository interface. MongoRepository comes with basic CRUD operations for us to use out of the box. Make our jobs easier.

The PersonRepository implementation is in the PersonDAO class. All of this will be done using the API.

Insert data (create)

In this case, the insert() method takes a Person object as an argument and inserts the Person details into MongoDB.

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

Get data (read)

Here, we define two ways to read data from MongoDB.

  • Get the owner information: getAllPersonInformation(), which returns a collection of Persons.
public Collection<Person> getAllPersonInformation() {
        return personRepository.findAll();
    }
  • To get information about a specific person: getPersonById() This method takes an ID as a parameter and returns the person information that matches the ID.
 public Optional<Person> getPersonInformationById(String id) {
        return personRepository.findById(id);
    }

Update existing data

In this case, updatePersonusingID ()method will take an ID and a 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);
    }

Delete the data

Here, the method deletePersonusingId () takes anID as an argument and deletes the Person data corresponding to that ID.

public void deletePersonUsingId(String id) { try { personRepository.deleteById(id); } catch (NoSuchElementException e) { e.printStackTrace(); }}

That’s it. All of this can be done using the APIs we provide in the controller. Test the application using PostMan. Free access to more learning materials: 3907814

conclusion

This is just a quick overview of the basic CRUD example, but the production-level code is cleaner, more detailed, and contains many scenarios. This example is far from it.

Below is a link to this project, which includes a docker-compose.yml and MongoDB images to help you run this example quickly!

The project’s GitHub repository link is here.