Spring Data MongoDB – Aggregation Grouping Example

In this tutorial, we will show you how to do the data grouping with Spring Data + MongoDB aggregation framework.

1. Test Data

domain.json

{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" }
{ "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"}
{ "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" }
{ "_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com" }
{ "_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com" }
{ "_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com" }
{ "_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com" }
{ "_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com" }
{ "_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com" }
{ "_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com" }
...
{ "_id" : 100, "domainName" : "test10.com", "hosting" : "godaddy.com" }

2. MongoDB Aggregation Example

MongoDB aggregation example to sum the total number of hosting :


db.domain.aggregate(
    {
	$match : {_id:{$lt:10}}
    },
    { 
	$group : {_id : "$hosting", total : { $sum : 1 }}
    },
    {
	$sort : {total : -1}
    }
);

Output


{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "hostgator.com", "total" : 3 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }

2. Spring Data + MongoDB Aggregation Example

This is the equivalent example in Spring Data MongoDB.

DomainDaoImpl.java

package com.mkyong.core.domain.dao;

//imports as static
import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.mkyong.core.domain.model.Domain;
import com.mkyong.core.hosting.model.HostingCount;
import java.util.List;

@Repository
public class DomainDaoImpl implements DomainDao {

	@Autowired
	MongoTemplate mongoTemplate;
	
	public List<HostingCount> getHostingCount() {
	
		Aggregation agg = newAggregation(
			match(Criteria.where("_id").lt(10)),
			group("hosting").count().as("total"),
			project("total").and("hosting").previousOperation(),
			sort(Sort.Direction.DESC, "total")
				
		);

		//Convert the aggregation result into a List
		AggregationResults<HostingCount> groupResults 
			= mongoTemplate.aggregate(agg, Domain.class, HostingCount.class);
		List<HostingCount> result = groupResults.getMappedResults();
		
		return result;
		
	}
HostingCount.java

package com.mkyong.core.hosting.model;

public class HostingCount {

	private String hosting;

	private long total;

	//...
}
More Examples
Refer to this official Spring data – Aggregation Framework Support

References

  1. MongoDB – Aggregation Concepts
  2. MongoDB – Aggregate And Group Example
  3. Spring.io – Aggregation Framework Support

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
???? ?????????
11 years ago

May yuo give me source code of this example please?.Unfortunately id doesn’t work for me. It give null result without any errors

???? ?????????
11 years ago

Ok. I solved my problem. I just commended ” match(Criteria.where(“_id”).lt(10))” May be it doesn’t work for me because i have LongNumber id

Arun Shiva
7 years ago

What is the Domain class

Arun Shiva
7 years ago

Can you please add the Domain class

ravi
7 years ago

I don’t want to give limit how should I do it.

choubani amir
8 years ago

does aggregation works with spring data mongodb in fields of nested array using DBREF?
I tried first aggregation of mongodb shell and I find that it does not work with references

Chiang
6 years ago
Reply to  choubani amir

If you want to use aggregations with references check out RelMongo https://github.com/kaiso/relmongo

pankaj
11 years ago

I am getting this error. Please help

java.lang.NoClassDefFoundError: org/springframework/data/mongodb/core/aggregation/AggregationOperation

Vincensius Adi Nugroho
11 years ago

hi, i got this error

errmsg” : “exception: aggregation result exceeds maximum document size (16MB)

guest
6 years ago

use the $AllowDiskUse in the Aggregation Query