繁体   English   中英

Spring数据MongoDB在多个字段上排序

[英]Spring data mongodb sort on multiple fields

我想使用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);

当我这样做时,它按DESC顺序在type上排序并createdDate 但是我想在type上使用DESC并在createdDatetype ASC

我试过了,

    sort(Sort.Direction.DESC, "type");
    sort(Sort.Direction.ASC, "createdDate");

但这仅在createdDatecreatedDate

您可以尝试这样。

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)
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM