How to get Count of aggregation query in spring mongo template

Zhozhe picture Zhozhe · Sep 25, 2015 · Viewed 7.7k times · Source

I'm using spring mongo template to run an agreegation query on mongodb. I'm wondering is there any way to find out the count of aggregation result in spring mongo template?

Here is my Aggregation sample :

Aggregation agg = newAggregation(Class1.class,
            match(criteria),
            group("prop1", "prop2")
            .avg("x").as("averageX")
        );

I just need to know how to get count of this aggregation result in spring mongo template.

Answer

Dr.Agos picture Dr.Agos · May 19, 2017

My response comes very late but it might help others. To get the count for an aggregation you need to add a new group at the end:

Add at the end of the aggregation -> Aggregation.group().count().as("count") to get the count

Aggregation aggregation = newAggregation(
            Aggregation.match(Criteria.where("x").is(x).and("y").exists(true)),
            Aggregation.group("x", "y"),
            Aggregation.group().count().as("count") 
);

To get the count:

Long.parseLong(results.getMappedResults().get(0).get("count").toString());