1 @RestController 2 @RequestMapping("test") 3 public class MongoStringSum { 4 @Autowired 5 private MongoTemplate mongoTemplate; 6 /** 7 * @Author: lpj 8 * @Date: 2021/8/28 20:37 9 * mongoDB統計字符串類型的數據和,以月份進行分組統計,且時間為字符串類型 10 */ 11 @GetMapping 12 public List<JSONObject> test() { 13 14 String tableName="你要統計的表名"; 15 String name = "name";//名稱列明 16 String date = "date";//日期列明 17 String score = "score";//分值列明 18 //其中日期的數據格式為字符串類型"2021-08-27 11:11:11" 19 //要統計的分值列數據為字符串類型"99.9","99.8" 20 Aggregation banciAggregation = Aggregation.newAggregation( 21 match(Criteria.where(name).is("張三")),//統計名稱為**的數據 22 //根據日期進行統計,日期為字符串數據,需特殊處理,這里是根據月份進行分組統計,截取日期字符串0-7則就為月份 23 Aggregation.project(date).andExpression(date).substring(0, 7).as("times") 24 //因為Mongo不能直接統計字符串求和操作,則對該字段的數據進行類型轉換,轉換為doubbo進行統計 25 .and(ConvertOperators.Convert.convertValueOf(score).to("double").onErrorReturn(0).onNullReturn(0)).as("class"), 26 //根據處理后的時間進行分組,對處理后的要統計的字段數據進行求和 27 Aggregation.group("times").sum("class").as("countSum")); 28 29 AggregationResults<JSONObject> banciAggregate = mongoTemplate.aggregate(banciAggregation, tableName, JSONObject.class); 30 List<JSONObject> results = banciAggregate.getMappedResults();//統計完成的數據就在該集合中,我們取出即可使用 31 return results; 32 } 33 34 }