MongoDB中统计计算Aggregation的使用

官方文档:https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

MongoDB中统计计算Aggregation的使用

MongoDB中统计计算Aggregation的使用

使用实例如下所示

使用一:通过日期分组之后求和。

public List<AbilityMonitor> queryAbilityMonitor(AbilityMonitorRequest reqBody){
    List<AbilityMonitor> list;
    Criteria criteria = Criteria.where("date").gte(reqBody.getFrom()).lte(reqBody.getTo());
    if(null != reqBody.getSelectGender()){
        criteria.and("gender").is(reqBody.getSelectGender());
        Query query = new Query(criteria);
        list = mMongoTemplate.find(query, AbilityMonitor.class,"AbilityMonitor");
    }else{
            Aggregation aggregation1 = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("date").first("date").as("date")
                        .sum("abilityLive1v1Active").as("abilityLive1v1Active")
                        .sum("abilityLive1PActive").as("abilityLive1PActive")
                        .sum("abilityRoom3PActive").as("abilityRoom3PActive")
                        .sum("abilityChat9PActive").as("abilityChat9PActive")
                        .sum("abilityChatHeadActive").as("abilityChatHeadActive"),
                Aggregation.sort(Sort.Direction.ASC, "date")
            );
        list = mMongoTemplate.aggregate(aggregation1,"AbilityMonitor",AbilityMonitor.class).getMappedResults();
    }
    return list;
}

使用二:不分组,直接求和。
public List<CumulativeMonitor> queryCumulativeMonitor(AbilityMonitorRequest request){
    if(null != request.getSelectGender()){
        Criteria criteria = Criteria.where("gender").is(request.getSelectGender());
        Query query = new Query(criteria);
        return  mMongoTemplate.find(query, CumulativeMonitor.class,"CumulativeMonitor");
    }else{
        Aggregation aggregation1 = Aggregation.newAggregation(
                Aggregation.group()
                        .sum("abilityLive1v1Total").as("abilityLive1v1Total")
                        .sum("abilityLive1PTotal").as("abilityLive1PTotal")
                        .sum("abilityRoom3PTotal").as("abilityRoom3PTotal")
                        .sum("abilityChat9PTotal").as("abilityChat9PTotal")
                        .sum("abilityChatHeadTotal").as("abilityChatHeadTotal")
        );
        AggregationResults<CumulativeMonitor> outputTypeCount1 = mMongoTemplate.aggregate(aggregation1,"CumulativeMonitor",CumulativeMonitor.class);
        return  outputTypeCount1.getMappedResults();
    }
}
上一篇:独立云虚拟主机 如何免费配置https加速呢?


下一篇:MongoDB模糊查询时带有括号的情况