有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Springboot中的java组计数聚集

Aggregation agg = Aggregation.newAggregation( 
other operations ////
Aggregation.group("name") .first("$$ROOT").as("doc").count().as("Total"), 
other operations ////
); 

这里我们将count存储为组操作的值,并存储在字符串变量“Total”中,如何以int格式获取count的值

注意:我使用Mongo模板


共 (1) 个答案

  1. # 1 楼答案

    如果要统计属于每个组的文档,应使用以下代码段:

    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来获得每个组的计数

    如果在分组文档之后做了其他事情,结果可能是另一个^ {< CD2>},并且必须考虑它,并改变描述聚合结果的类。p>