Most of you may be familiar working with Relational Databases such as MySQL, MS SQL Server, Oracle etc. and those are the most common databases used in Spring Boot Applications. For most of the programmers, it is more convenient working with Relational Database rather than No-SQL databases since there is a huge community behind Relational Databases if you need for any assistance. But however in certain occasions we have to work with No-SQL Databases such as MongoDB etc.
So, today let's discuss how to cooperate and work with the No-SQL databases such as MongoDB inside the Spring Boot application context.
In here we use MongoTemplate to execute the query and extract the result using Java as the Programming Language.
Use Case for explain this task is:
Let's take an enterprise application which have the feature of sending OTPs to verify their user's true identity (virtual-identity) during their login process to the application. So, in this scenario the database will store all the informations such as OTP Received Date, Created Date Time, OTP Status, Validity Period etc. But when you expecting a different output result from that collection such as Total OTP Count and the Total User Logged In count against each given date.
Note:- The expected output result is shown below.
Note:- The expected output result is shown below.
So, in this tutorial we are using MongoTemplate with Spring Boot to perform this task. First of all before dig into our task, there are some pre requirements that we need to be setup as pre requirements. Firstly you need to create a new SpringBoot Application.
Secondly, you need to place the below spring boot mongodb dependancy to your pom.xml file of your project inside the <dependancies></dependancies> tag.
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
Finally in the application.yml file which is located inside the resources folder of your newly created project, you need to define these property configurations for spring boot mongodb.
spring:data:mongodb:host: <mongo-db-database-server-ip>port: <mongo-db-port>username: <mongo-db-database-username>password: <mongo-db-database-password>database: <mongo-db-database>
After setting up the above property configurations, we are about to continue with our task. So, now. let's simply create a simple service which provides the functionality of retrieving data from the mongo database where the output matches with the desired output.
OtpGenerationReportService.java
OtpProjDto.java
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class OtpProjDto implements Serializable {
private String createdAt;
private BigInteger totalCount;
private BigInteger loggedIn; }
0Comments