最近項目用到了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; }