rohit
rohit

Reputation: 1003

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.

Upvotes: 9

Views: 14235

Answers (4)

siddhartha agarwal
siddhartha agarwal

Reputation: 59

Simple sorting without Aggregation object

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;

//query: existing mongo query
//mongoTemplate: @Autowired MongoTemplate object
//First create a list of Sort.Order and add multiple criteria's

List<Sort.Order> sortOnMultipleFIelds = new ArrayList<>();
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field1"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.ASC, "Field2"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field3"));


//Apply it on Query
            query.with(Sort.by(sortOnMultipleFIelds);

//Execute query
            List<ClassName> resultList= mongoTemplate.find(query, ClassName.class); 

Upvotes: 0

Alexey Simonov
Alexey Simonov

Reputation: 425

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

Upvotes: 4

Ashish Bakwad
Ashish Bakwad

Reputation: 811

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

Upvotes: 3

s7vr
s7vr

Reputation: 75914

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

Upvotes: 6

Related Questions