Home:ALL Converter>Spring data mongodb sort on multiple fields

Spring data mongodb sort on multiple fields

Ask Time:2017-01-18T23:05:27         Author:rohit

Json Formatter

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.

Author:rohit,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41722765/spring-data-mongodb-sort-on-multiple-fields
Ashish Bakwad :

You can create order list and use it for sort like this\n\nList<Order> orders = new ArrayList<>();\norderQuery.add(new Order(Direction.DESC, \"createdDate\"));\nSort sorts = new Sort(orders.toArray(new Order[orders.size()])); \nAggregation agg = newAggregation(\n match(Criteria.where(\"userId\").is(userId)),\n sort(sorts)\n);\n",
2017-01-21T09:25:46
s7vr :

You can try something like this.\n\nAggregation agg = newAggregation(\n match(Criteria.where(\"userId\").is(userId)),\n sort(Sort.Direction.DESC, \"type\").and(Sort.Direction.ASC, \"createdDate\")\n);\n",
2017-01-18T15:48:16
Alexey Simonov :

Little bit late, but for other people...\nTry this (for spring-data):\n\nprivate static final Sort NOTE_SORT = new Sort(new Sort.Order(Sort.Direction.ASC, \"seen\"),\n new Sort.Order(Sort.Direction.DESC, \"date\"),\n new Sort.Order(Sort.Direction.ASC, \"done\"));\n",
2017-11-04T08:12:59
yy