首页 > 技术文章 > mongoTemplate 聚合排序不生效问题

donglulu 2020-04-23 15:44 原文

最近项目用到了MongoDB,在使用聚合的时候发现排序没有生效.  后来发现是sort位置原因.

public List<TrackTrace> findPoint(List<String> jobNos) {

        Sort sort = new Sort(Sort.Direction.DESC, "traceDate");
        Aggregation agg =
                Aggregation.newAggregation(
                        Aggregation.project("jobNo", "points", "traceDate", "time"),
                        Aggregation.match(Criteria.where("jobNo").in(jobNos)),
                        Aggregation.sort(sort),//在聚合之前对数据进行排序
                        Aggregation.group("jobNo")
                                .first("jobNo").as("jobNo")
                                .first("points").as("points")
                                .first("traceDate").as("traceDate")
                );
        AggregationResults<TrackTrace> durationData =
                mongoTemplate.aggregate(agg, "TrackTrace", TrackTrace.class);
        List<TrackTrace> traces = durationData.getMappedResults();
        return traces;
    }

 

推荐阅读