Search code examples
javamongodbmongodb-queryaggregation-frameworkspring-data-mongodb

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.


Solution

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