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 }
  • 相关阅读:
    SVN 主干(trunk)、分支(branch )、标记(tag)
    HTML的img标签:alt属性和title属性
    HTML的img标签:alt属性和title属性
    Eclipse远程调试Tomcat
    Eclipse远程调试Tomcat
    使用 Eclipse 远程调试 Java 应用程序
    使用 Eclipse 远程调试 Java 应用程序
    14.Windows 与 Linux 文件共享
    13.远程登录 Linux
    12.Linux 网络配置
  • 原文地址:https://www.cnblogs.com/859630097com/p/15201108.html
Copyright © 2011-2022 走看看