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
.
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.
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.
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.
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")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With