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;
/**
* @ClassName MongoStringSum
* @Author lpj
* @Date 2021/12/17 14:37
**/
@RestController
@RequestMapping("test")
@ApiIgnore
public class MongoStringSum {
@Autowired
private MongoTemplate mongoTemplate;
/**
* @Author: lpj
* @Date: 2021/8/28 20:37
* mongoDB统计字符串类型的数据和,以月份进行分组统计,且时间为字符串类型
*/
@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("张三")),//条件筛选,统计名称为**的数据
//根据日期进行统计,日期为字符串数据,需特殊处理,这里是根据月份进行分组统计,截取日期字符串0-7则就为月份
Aggregation.project(date).andExpression(date).substring(0, 7).as("times")
//因为Mongo不能直接统计字符串求和操作,则对该字段的数据进行类型转换,转换为doubbo进行统计
.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;
}
}