mongo根据字段值进行排序,类似case when的方式实现
背景:resourceType为1、2、3、4,将前端传来的类型排到最前边,然后再按照浏览量排序。使用的数据库为mongo,=所以采用类似case when的方式实现该功能,主要代码如下:
//查询条件
Criteria criteria = Criteria.where("validFlag").is(1)
Integer pageNum = relevantResourceQo.getPageNum();
Integer pageSize = relevantResourceQo.getPageSize();
// 生成冗余结果字段,如果字段值和传值相等,赋值为1,其他值赋值为0
ConditionalOperators.Cond condOperation = ConditionalOperators.when(Criteria.where("resourceType").is(param.getResourceType()))
.thenValueOf("1")
.otherwise("0");
//返回的字段
ProjectionOperation project = Aggregation.project("id","resourceName","resourceType",
"fileId","collectNum","browseNum");
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
project.and(condOperation).as("sortNo"),
Aggregation.sort(Sort.by(Sort.Order.desc("sortNo"), Sort.Order.desc("browseNum"))),
Aggregation.skip((long)(pageNum - 1) * pageSize),
Aggregation.limit(pageSize));
List<RelevantResourceVo> results = mongoTemplate.aggregate(aggregation, ResourceEntity.class, RelevantResourceVo.class).getMappedResults();
long count = mongoTemplate.count(new Query(criteria), ResourceEntity.class);
Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
Page<RelevantResourceVo> page = new PageImpl<>(results, pageable, count);
如有更好的实现方式,欢迎提出。