简体   繁体   中英

Spring data mongodb sort on multiple fields

I want to sort on multiple fields in MongoDB using Spring data for MongoDB. Currently I am trying to achieve this using aggregation:

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

When I am doing this, it is sorting on the type and createdDate on DESC order. But I want DESC on type and ASC on createdDate .

I tried,

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

but this is sorting only on createdDate .

You can try something like this.

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

Little bit late, but for other people... Try this (for 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"));

You can create order list and use it for sort like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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