5

我正在使用 spring mongo 模板在 mongodb 上运行协议查询。我想知道有没有办法找出spring mongo模板中的聚合结果计数?

这是我的聚合示例:

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

我只需要知道如何在 spring mongo 模板中获取此聚合结果的计数。

4

2 回答 2

7

我的回复来得很晚,但它可能会帮助其他人。要获取聚合的计数,您需要在最后添加一个新组:

在聚合末尾添加 -> Aggregation.group().count().as("count") 获取计数

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

要获得计数:

Long.parseLong(results.getMappedResults().get(0).get("count").toString());
于 2017-05-19T14:44:28.990 回答
1

对于春季数据 mongo 2.1.4

如果您假设您的返回班是这样的:

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

您可以使用以下代码:

1.Hold分组数据:

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

2.仅获取计数:(分组在您使用first(...)last(...)之后使用之前不会生效)

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**/
于 2019-07-16T10:46:41.057 回答