zoukankan      html  css  js  c++  java
  • 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         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 }
  • 相关阅读:
    idea 2017版破解
    UIRecorder 学习了解
    简单应用单例模式
    线程安全的单例模式(有参and无参)
    批量删除和批量修改(参数使用list)
    简单线程池开启线程
    随机数生成
    网络延迟-tc工具使用简单说明
    c++高级元编程 第一部分,第一节,第一小节
    Writing_Bug_Free_C_Code_Chapter_2_Know_Your_Environment
  • 原文地址:https://www.cnblogs.com/859630097com/p/15201108.html
Copyright © 2011-2022 走看看