How to get Count of aggregation query in spring mongo template

好久不见. 提交于 2019-12-14 02:19:34

问题


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.


回答1:


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());



回答2:


for spring data mongo 2.1.4

if you assume your return class is like this:

class Output{
  Object x;
  Object y;
  /**getter and setter**/
}

you can use this code:

1.Hold grouping data:

AggregationResults<Output> result = 
                mongoTemplate.aggregate(
                        agg ,
                        "YOUR_DOCUMENT",
                        Output.class
                );
int count = result.getMappedResults().size();

2. only get count: (grouping not effect until you use first(...) or last(...) usage after that)

Aggregation agg = Aggregation.newAggregation(
                      match(criteria),
                      count().as("x")/*using x only for mapping count*/
                   );
    AggregationResults<Output> result = 
                    mongoTemplate.aggregate(
                            agg ,
                            "YOUR_DOCUMENT",
                            Output.class
                    );
    int count = result.getMappedResults().get(0).getX().get(0);/**o_O**/


来源:https://stackoverflow.com/questions/32785114/how-to-get-count-of-aggregation-query-in-spring-mongo-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!