MongoTemplate聚合查询

1、统计缺失站点数量及信息,按数量倒序排列

表结构

{
    "datetime" : "20200101000000",
    "missid" : [ 
        "54748", 
        "54859", 
        "54946"
    ],.....
}
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
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.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


/*
 * project:列出所有本次查询的字段,包括查询条件的字段和需要搜索的字段;
 * match:搜索条件criteria
 * unwind:某一个字段是集合,将该字段分解成数组
 * group:分组的字段,以及聚合相关查询
 *      sum:求和(同sql查询) group("type").sum("size").as("total")
 *      count:数量(同sql查询) group("missid").count().as("count")
 *      as:别名(同sql查询)
 *      addToSet:将符合的字段值添加到一个集合或数组中
 * sort:排序
 * skip&limit:分页查询
 */
	public String getLostStationSumByTimeRange(String timeRange) {
		String[] times = timeRange.split(",");
		Criteria criteria = Criteria.where("datetime").gte(times[0]).lte(times[1]);
		Aggregation aggregation = Aggregation.newAggregation(match(criteria), project("missid"),
				Aggregation.unwind("missid"), group("missid").count().as("count"),
				project("count").and("missid").previousOperation(), Aggregation.sort(Sort.Direction.DESC, "count"));
		AggregationResults ar = mongoTemplate.aggregate(aggregation, "XXLog",
				SubjectCount.class);
		List lists = ar.getMappedResults();
		for(SubjectCount sub : lists) {
			Station s = mongoTemplate.findOne(new Query(Criteria.where("stationid").is(Integer.parseInt(sub.getMissid()))), Station.class,"station");
			if(s!=null) {
			sub.setName(s.getName());
			sub.setArea(s.getArea());
			sub.setCity(s.getCity());
			}
		}
		return new Gson().toJson(lists);
	}

查询结果

[
{
"missid": "54659",
"count": 25,
"name": "xx",
"city": "xx",
"area": "xx"
},
{
"missid": "54862",
"count": 25,
"name": "xx",
"city": "xx",
"area": "xx"
}....]

2、统计某段时间内访问API的最新时间

public Object getAPINameByTimeRange(String timeRange) {
		String[] times = timeRange.split(",");
		Criteria criteria = Criteria.where("accesstime").gte(times[0]).lte(times[1]);
		Aggregation aggregation = Aggregation.newAggregation(match(criteria), 
				sort(Sort.Direction.DESC, "accesstime"), //倒序
				group("apiname").first("accesstime").as("accesstime"), //按api名字分组,取第一个时间
				project("apiname", "accesstime").and("apiname").previousOperation());
		AggregationResults ar = mongoTemplate.aggregate(aggregation, "monitor", APIMonitor.class);
		List list = ar.getMappedResults();
		
	}

3、按天统计

MongoDB3.4
public Object getAPIByDay(String timeRange) {
		String[] times = timeRange.split(",");
		Criteria criteria = Criteria.where("accesstime").gte(times[0]).lte(times[1]);
		Aggregation aggregation = Aggregation.newAggregation(match(criteria),
				project("day").andExpression("substr(accesstime,0,8)").as("time"), //转换格式
				group("day", "time").count().as("total"), 
				sort(Sort.Direction.DESC, "time"));
		AggregationResults ar = mongoTemplate.aggregate(aggregation, "Monitor", APIMonitor.class);
		List list = ar.getMappedResults();
	}
	或者MongoDB3.6及以上
	Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.project(""inDate")
                        .andExpression("{$dateToString:{format:'%Y年%m月%d日',date:'$inDate',timezone: 'Asia/Shanghai'}}").as("dateToString")
        );

结果

[{
"total": 1933,
"time": "20200526"
},
{
"total": 27550,
"time": "20200525"
}]

你可能感兴趣的:(mongodb)