【问题标题】:Group count Aggeration in SpringbootSpring Boot中的组计数聚合
【发布时间】:2021-05-18 17:23:59
【问题描述】:
Aggregation agg = Aggregation.newAggregation( 
other operations ////
Aggregation.group("name") .first("$$ROOT").as("doc").count().as("Total"), 
other operations ////
); 

这里我们将组操作的计数值存储在String变量“Total”中,我们如何才能得到int格式的计数值?

注意:我使用 Mongo 模板。

【问题讨论】:

  • 在对文档进行分组后,您如何使用 Total 值? group 运算符返回 count 的数值,因为 count() 方法在查询中生成 $sum: 1。所以Total 不能是字符串。并向我们​​展示mongoTemplate.aggregate 的召唤。你用什么类来输出?
  • 哦,我不确定。我需要获取组操作的总大小(计数)。我使用 Pojo 类。 MongoTemplate.aggregate(agg, class,class).getMappedResults();

标签: java mongodb spring-boot aggregation-framework


【解决方案1】:

如果你想统计属于每个组的文档,你应该使用下面的代码sn -p:

public class GroupCount {
    public String name;
    public YourDocument doc;
    public Long count;
}

...

Aggregation aggregation = Aggregation.newAggregation( 
    // some aggregation operations
    Aggregation.group("name")
        .first("$$ROOT").as("doc")
        .count().as("total")
); 
AggregationResults<GroupCount> results = mongoTemplate.aggregate(
        aggregation, YourDocument.class, GroupCount.class);
List<GroupCount> groupCounts = results.getMappedResults();

YourDocument 是一个描述您分组的文档的类。 GroupCount 是一个代表聚合结果的类(我建议name 字段是一个字符串)。

您准备好聚合管道并调用aggregate 方法。它返回描述为GroupCount 对象的聚合结果。然后您可以通过调用getMappedResults 来获取每个组的计数。

如果你在对文档进行分组后做其他事情,结果可能不是GroupCount,你必须考虑并更改描述聚合结果的类。

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 2019-02-01
    • 2021-08-15
    • 2021-06-15
    • 2021-08-03
    • 2019-05-21
    • 1970-01-01
    • 2017-04-23
    • 2015-02-02
    相关资源
    最近更新 更多