需要进行统计的数据字段:

统计代码:
package com.form.formdata.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.ConvertOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
@RestController
@RequestMapping("test")
@ApiIgnore
public class MongoStringSum {
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping
public List<JSONObject> testSum() {
String tableName = "你要统计的表名";
String name = "name";
String date = "date";
String score = "score";
Aggregation banciAggregation = Aggregation.newAggregation(
match(Criteria.where(name).is("张三")),
Aggregation.project(date).andExpression(date).substring(0, 7).as("times")
.and(ConvertOperators.Convert.convertValueOf(score).to("int").onErrorReturn(0).onNullReturn(0)).as("class"),
Aggregation.group("times").sum("class").as("countSum"),
Aggregation.project("times", "countSum").and("times").previousOperation());
AggregationResults<JSONObject> banciAggregate = mongoTemplate.aggregate(banciAggregation, tableName, JSONObject.class);
List<JSONObject> results = banciAggregate.getMappedResults();
return results;
}
}
统计出的效果:
