mongoTemplate聚合统计字段类型为字符串的数据,根据时间日期月份进行统计,日期也为字符串

时间:2021-08-28
本文章向大家介绍mongoTemplate聚合统计字段类型为字符串的数据,根据时间日期月份进行统计,日期也为字符串,主要包括mongoTemplate聚合统计字段类型为字符串的数据,根据时间日期月份进行统计,日期也为字符串使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 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         Criteria criteria = new Criteria();
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 }

原文地址:https://www.cnblogs.com/859630097com/p/15201108.html