我想使用MongoDB的Spring数据对MongoDB中的多个字段进行排序。目前我正在尝试使用聚合实现此目的:
Aggregation agg = newAggregation(
match(Criteria.where("userId").is(userId)),
sort(Sort.Direction.DESC, "type", "createdDate"),
);
AggregationResults<MyBean> results = mongoOperations.aggregate(agg, MyBean.class, MyBean.class);
当我这样做时,它正在按照type
顺序对createdDate
和DESC
进行排序。但是我希望DESC
和type
上的ASC
和createdDate
。
我试过了,
sort(Sort.Direction.DESC, "type");
sort(Sort.Direction.ASC, "createdDate");
但这只是在createdDate
上排序。
你可以尝试这样的事情。
Aggregation agg = newAggregation(
match(Criteria.where("userId").is(userId)),
sort(Sort.Direction.DESC, "type").and(Sort.Direction.ASC, "createdDate")
);
有点晚了,但是对于其他人......尝试这个(对于spring-data):
private static final Sort NOTE_SORT = new Sort(new Sort.Order(Sort.Direction.ASC, "seen"),
new Sort.Order(Sort.Direction.DESC, "date"),
new Sort.Order(Sort.Direction.ASC, "done"));
您可以创建订单列表并将其用于此类排序
List<Order> orders = new ArrayList<>();
orderQuery.add(new Order(Direction.DESC, "createdDate"));
Sort sorts = new Sort(orders.toArray(new Order[orders.size()]));
Aggregation agg = newAggregation(
match(Criteria.where("userId").is(userId)),
sort(sorts)
);