2

I want to get the total number of results for an aggregation using mongotemplate.

To clarify - for queries we can use: mongoTemplate.count(query, collectionName), which gets the number of results without considering limit / skip.

However, I couldn't find something similar for mongotemplate aggregations... The total results are needed because we use pagination, and need to know the total number without the limit / skip.

EDIT: for example, if I have the following collection A with 10 documents:

{ field1 : ... , field2 : ... , }, ...

I can create a query to get documents using mongotemplate :

Query query = new Query();
query.limit(5);
List<?> queryResults = this.mongoTemplate.find(query, A.class , "A") // will return only 5 results
long count = this.mongoTemplate.count(query, collectionName); // will return 10, because that's the total number result

Now, if I have an aggregation instead of query:

    List<AggregationOperation> aggregationOperations = new ArrayList<AggregationOperation>();

    aggregationOperations.add(Aggregation.match(...));
    aggregationOperations.add(Aggregation.group(...));
    aggregationOperations.add(Aggregation.limit(someLimit));

    AggregationResults<?> aggregationResults = 
    this.mongoTemplate.aggregate(
                            Aggregation.newAggregation(aggregationOperations), "A", 
AggregationResults.class);

I want some way to get the total number of results in the aggregation - similar to "count" for the query.

Ayelet
  • 1,713
  • 9
  • 29
  • 43
  • Could you add a little bit of more context with some sample documents and the expected output? – chridam Jan 04 '16 at 11:28
  • @chridam please see my edit – Ayelet Jan 04 '16 at 13:05
  • I am also facing same issue. please mention some way for getting count like query.count for aggregation. I have used this answer trick to solve my problem. https://stackoverflow.com/questions/32785114/how-to-get-count-of-aggregation-query-in-spring-mongo-template – Amol Suryawanshi Nov 21 '17 at 10:48

1 Answers1

2

You can do it like this

operations.add(Aggregation.group().count().as("count"));

Document rawResults = getMongoTemplate().aggregate(
            Aggregation.newAggregation(operations),
            collectionName,
            entityClass)
         .getRawResults();

    List<Map<String, Object>> results = (List<Map<String, Object>>) rawResults.get("results");

    if (CollectionUtils.isNotEmpty(results)
        && results.get(0) != null 
        && results.get(0).containsKey("count")) {
        Integer count = (Integer) results.get(0).get("count");
        return count.longValue();
    }
    return 0;

}
nestdimmy
  • 71
  • 7