Are you building an application and in process of evaluating different databases? NoSQL databases bring lots of value on the table compared to relational databases. The nature of application data is going to influence the database selection decision. Let’s explore how to use Aggregation in MongoDB.

If you are looking forward to storing document nature of data like company profile, insurance policy documents, customer data, product data, asset information etc. then MongoDB is the right choice. It’s the most preferred choice by global leaders in industries like telecommunications, finance, gaming, healthcare, retail. In this blog we will explore the data aggregation feature of MongoDB.

What we want to achieve

With digital adoption at the core of enterprises, systems keep on generating big data. If you have thousands of global records and want to present the records by Country, aggregation helps to make high performance queries on MongoDB.

Accessing MongoDB using MongoRepository

Let’s start with creating Repository patterns on collection in the Java based Springboot application. To be able to access a mongoDB collection, create a class for the collections with variables as collection’s fields. On top of this class, give the annotation @Document(“collectionName”). The field with objectId of mongoDB should be annotated with @Id.

 @Document(“companyTable”)
 public class Company{
  @Id
  String Id;
  String companyName;
  String companyDescription
  String country;
  // add other fields
 }

With the document class done, create an interface extending MongoRepository with document class and String class as parameterized arguments to MongoRepository. The interface is to be annotated with @Repository

 @Repository
 public interface CompanyDBRepository extends MongoRepository{ }

Given below are few abstract method examples through which data can be fetched with respect to table fields.

 @Repository
 public interface CompanyDBRepository extends MongoRepository{
  Company findByCompanyId (String companyId);
  List findByStatusAndUpdatedDateGreaterThan(String status, Date updatedDate);
  List findByCompanyNameIgnoreCase(String companyName);
 }

In the first method, a single query is fetched w.r.t. a field. In the second and third method, a list of a class is fetched with usage of And, Or, greater than keywords acting with respect to fields provided. Java Compiler creates the query according to the naming of the method.

If the query is more complex, the method can also be applied with the ‘@Query’ annotation to define the queries. Methods with query annotation need not follow MongoRepository’s naming conventions.

 @Query("{'deletedStatus': ?0 ,'updatedDate': {$gte: ?1}}")
 List findByStatusesAndUpdatedDate(String deletedStatus, Date updatedDate);

The usage of repositories over MongoTemplates makes them very convenient and powerful to use, eventually saving time for the programmer. For more details, refer to following link:

https://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mongo.repositories.html

Aggregation in MongoDB using SpringBoot Repository

In this case we want to find companies group by the country. Let’s create a class to fetch the aggregation.

 public class CompanyAggregate {
  @Id
  private String countryId;    // to fetch countryId or countryCode stored in company
  private List countryName; // using list because we will use ‘$addToSet’
  private int total;    // to fetch total number of companies
 }

Now, in the repository, our aggregation should be in ‘Company’ class’s repository as show below:

 @Repository  public interface CompanyDBRepository extends MongoRepository{
  @Aggregation(pipeline = {"{$match: {status:ACTIVE}}","{$group: { _id : $countryId, countryName : { $addToSet : $country}, total : {$sum:1}}}","{$sort: {total:-1}}"})
  List groupByCountryIdAndCountry();
 }
In the query pipeline above, $match was used to get only active companies and not the soft deleted companies. $group is used to fetch the aggregation data and $sort to sort the queries according to the total in descending order.

Summary

With MongoDB Repository patterns and aggregation queries, we can manage to group the big data records in a few milliseconds. Along with gzip on Java project, this provides an intuitive and high performance experience to the users. Most of the Dashboard queries can take advantage of MongoDB advanced features.

Patterns7 Technologies has expertise & experience building scalable applications using MongoDB. Let’s get in touch on exploring how we can collaborate creating differentiated experiences for your Customers.

Get in touch

Explore how Patterns7 can help on your enterprise digital transformation journey. Let’s connect !!

info@patterns7tech.com