Work with Mongo DB using MongoTemplate in Spring Boot

 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.



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

// Uses "createdAt", "status" columns to calculate totals and set aliases as "otpDate" and "verifyStatus"

ProjectionOperation projection = project("createdAt", "status")

    .and(DateOperators.DateToString.dateOf("createdAt").toString("%Y-%m-%d")).as("otpDate")

   .and(AccumulatorOperators.Sum.sumOf(ConditionalOperators.when(ComparisonOperators.Eq.valueOf("status").equalToValue("VERIFIED"))

    .then(1).otherwise(0))).as("verifyStatus"); 


// Joined the two group result into one result 

GroupOperation totalCount = group("otpDate").count().as("totalCount") .push("verifyStatus").as("loggedIn"); 


// Filter-data for given specific-dates-range 

MatchOperation match = match(Criteria.where("createdAt").gte(from).lte(to)); 



// Sort the result to ascending order by _id 

SortOperation sortOperation = sort(Sort.Direction.ASC, "_id");


// Create Aggeregation 

final TypedAggregation<Otp> aggregation = newAggregation( Otp.class, match, projection, totalCount, sortOperation);

// Execute the Aggregate 

mongoTemplate.aggregate(aggregation, OtpGenerationDataDto.class).getMappedResults();

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; 
    }



Actual Result :







Buy website traffic cheap

Post a Comment

0 Comments