SpringBoot+mongodb实现分组统计、时间范围查询、去重排序查询、组合排序
目录
一、分组统计(Aggregation)
1.按某字段分组统计
/**
* 根据分类名称 分组统计销售数量
* @param dataType 1:本日 2:本月 3:本年
* @return
*/
@RequestMapping("/findInfoByGroup")
public List<Map> findInfoByGroup(){
//从mongodb里获取满足条件的记录 status:状态 1:上架 2:下架
Criteria criteria = Criteria.where("status").is(1);
//聚合函数查询统计信息
Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
//按分类名称 统计 销售数量
Aggregation.group("category").sum("sale_num").as("total"),
//按照total降序
Aggregation.sort(Sort.Direction.DESC,"total")
);
AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(aggregation,Product.class,Map.class);
List<Map> list = aggregationResults.getMappedResults();
return list;
}
category:要分组的字段
sale_num:要统计的字段
total:别名
返回结果:
[
{
"_id": "口红",
"total": 2224.0
},
{
"_id": "面膜",
"total": 997.0
},
{
"_id": "文具",
"total": 799.0
},
{
"_id": "男装",
"total": 675.0
},
{
"_id": "女装",
"total": 448.0
}
]
_id本来应该是对应查询的字段,没有处理,spring会将分组字段自动转换为_id
2.多字段分组统计
/**
* 根据分类名称和规格 分组统计销售数量
* @param
* @return
*/
@RequestMapping("/findInfoByGroup1")
public List<Map> findInfoByGroup1(){
//从mongodb里获取最新的一条记录 status:状态 1:上架 2:下架
Criteria criteria = Criteria.where("status").is(1);
//聚合函数查询统计信息
Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
//按分类名称 统计 销售数量
Aggregation.group("category","specification").sum("sale_num").as("total"),
//按照total降序
Aggregation.sort(Sort.Direction.DESC,"total")
);
AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(aggregation,Product.class,Map.class);
List<Map> list = aggregationResults.getMappedResults();
return list;
}
返回结果:
[
{
"_id": {