官方文档: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(); } }