9

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.

4 Answers 4

6

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")
);
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.