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

问题描述 投票:2回答:3

我想使用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顺序对createdDateDESC进行排序。但是我希望DESCtype上的ASCcreatedDate

我试过了,

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

但这只是在createdDate上排序。

java mongodb mongodb-query aggregation-framework spring-data-mongodb
3个回答
2
投票

你可以尝试这样的事情。

Aggregation agg = newAggregation(
        match(Criteria.where("userId").is(userId)),
        sort(Sort.Direction.DESC, "type").and(Sort.Direction.ASC, "createdDate")
);

2
投票

有点晚了,但是对于其他人......尝试这个(对于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"));

0
投票

您可以创建订单列表并将其用于此类排序

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)
);
© www.soinside.com 2019 - 2024. All rights reserved.