MongoDB中统计计算Aggregation的使用

2021/4/30 19:27:30

本文主要是介绍MongoDB中统计计算Aggregation的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

使用实例如下所示

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

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


这篇关于MongoDB中统计计算Aggregation的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程