Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
rohit Avatar asked Jan 18 '17 15:01

rohit


People also ask

How do I sort a field in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Which is better MongoTemplate or MongoRepository?

MongoTemplate is a bit more lower level where you need to write your own queries. With embedded documents and denormalization it can be easier to write complex queries with MongoTemplate. For simple things I would use MongoRepository. I've seen some examples where both are used together in a hybrid approach.


1 Answers

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")
);
like image 102
s7vr Avatar answered Oct 10 '22 00:10

s7vr