Simple and Easy way to connect MongoDB Atlas with Spring Boot

In this brief article, we will see how we can use MongoDB Atlas with Spring Boot. MongoDB Atlas is Database as a Service. With database available on the cloud you can scale it as and when you need.

Software used

  • Spring Boot 2.0.6.RELEASE
  • MongoDB Atlas
  • Java 8
  • Maven
  • Eclipse

POM

Spring has always made development easy. For our POC as well we are using pre-built dependencies for MongoDB. Along with spring-boot-starter-data-mongodb we will use Project Lombok for easy POJO management.

MongoDB Atlas URL

To connect to MongoDB on the cloud you need to have the exact URL of your database with user and password. You can get this URL in your Atlas account as shown below

For our example, we have added below in our application.properties

You may have to change IP whitelisting as well because by default MongoDB Atlas won’t allow connecting from any IP address.

Define Collection

MongoDB is a NoSQL database, so it uses collections concept instead of tables. We will define our collection java mapping as below

The java class also has a convenience constructor defined.

Define Repository

As we are using Spring Data for MongoDB, defining a repository is as easy as adding an interface like below

That’s it, with above interface you will get access to all the CRUD operations around the MongoDB collection. If you need you can add some methods for your convenience as well

You can see that the interface supports methods based on field names as well as it supports the query based on JSON.

Custom MongoDB Repository

Apart from the standard Spring Data Repository, you can define your own as well. In that case, you can use MongoTemplate. A sample is also included below for reference

Implementation

The implementation is self-explanatory and I hope does not require any details.

Running the example

As we are using Spring Boot, we will add a command line runner with all the utility methods in it.

The output

Also below is the actual data from our MongoDB instance.

Conclusion

In this article we have seen, how easy it is to connect to a NoSQL MongoDB Cloud instance with Spring Boot. Please feel free to comment or ask a question or two.

You can find the complete source code at our GIT repository.

Download Code

Add a Comment

Your email address will not be published. Required fields are marked *