54

I'm fairly new on mongodb, and while I'm trying to make ordered mongodb query. But spring data mongodb's sort method is deprecated. So I used org.springframework.data.domain.Sort:

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC,"pdate"));
return mongoTemplate.find(query, Product.class);

I used this code block. But its not sorting the data. So can you prefer to use any useful method for this practice?

2
  • Your code looks correct, can you elaborate how did you come into conclusion "its not sorting the data" Commented Aug 29, 2013 at 23:01
  • 2
    they are not ordered date ascending on the page Commented Aug 30, 2013 at 5:45

11 Answers 11

44

You can define your sort in this manner to ignore case:

new Sort(new Order(Direction.ASC, FIELD_NAME).ignoreCase()
Sign up to request clarification or add additional context in comments.

4 Comments

thanks , that was what I mean years ago in my answer, I'm accepting your answer.
You can actually pass a comma delimited list (or pre-constructed List) to the Sort constructor and define multiple ordering criteria!
It doesn't work at me, with newest MongoDb, strange... I've got exception with Mongo and code like that... java.lang.IllegalArgumentException: Given sort contained an Order for username with ignore case! MongoDB does not support sorting ignoreing case currently!
This is deprecated now. Use Sort.by(Sort.Direction.ASC, FIELD_NAME)) instead
28

NEW ANSWER - Spring Data Moore

Use Sort.by

Query().addCriteria(Criteria.where("field").`is`(value)).with(Sort.by(Sort.Direction.DESC, "sortField"))

Comments

19

When you've written a custom query in your repository then you can perform sorting during invocation. Like,

Repository

@Query("{ 'id' : ?0}")
List<Student> findStudent(String id, Sort sort);

During invocation

Sort sort = new Sort(Sort.Direction.ASC, "date")
List<Student> students = studentRepo.findStudent(1, sort);  

I hope this helps! :)

Comments

8

This is how you sort a field value by Descending order. My field value is "nominationTimestamp", but for you it could be "firstName" for example.

List<Movie> result = myMovieRepository.findAll(Sort.by(Sort.Direction.DESC, "nominationTimestamp")); 

myMovieRepository is an instance of whatever class extends MongoRepository<>.

1 Comment

Please provide an explanation with your code. Codes without any explanation are going to be deleted.
6
query.with(new Sort(Sort.Direction.ASC, "timestamp"));

remember sort parameter as field, 1 or -1 to specify an ascending or descending sort respectively.

1 Comment

Can we use query.with() to sort on multiple fields ? e.g query.with(new Sort(Sort.Direction.ASC, "timestamp")).with(new Sort(Sort.Direction.DESC,"name"));
4

You can use aggregation for sorting your data. You have to use matching and grouping criteria for aggregation query and unwind your field.

AggregationOperation match = Aggregation.match(matching criteria);
AggregationOperation group = Aggregation.group("fieldname");
AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "fieldname");
Aggregation aggregation = Aggregation.newAggregation(Aggregation.unwind("fieldname"),match,group,sort);

Comments

4

This one worked for me:

query.with(Sort.by(Sort.Order.asc("pdate")));

Comments

3

spring-data-commons version 2.3.5+

The Sort constructor is private, so:

Query query = new Query();
query.with(Sort.by(Sort.Direction.ASC,"pdate"));
return mongoTemplate.find(query, Product.class);

Comments

2

If you always need to sort data in same direction add this to repository:

@Query(sort = "{'view': -1}")
Page<BlogModel> findTopBlogList(Pageable pageable);

Comments

1

You can use Aggregation in repository

Repository

  @Aggregation(pipeline ={
    "{$match: { id : ?0 }",
    "{$sort: {date: 1}}",
    "{$limit: 1}"
  }
  Optional<Student> findStudent(String id);

Comments

0

I'm using TypedAggregation with mongoTemplate in spring data to sort and limit the results set.

import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;
import org.springframework.data.domain.Sort.Direction;

TypedAggregation<ObjectType> agg = newAggregation(ObjectType.class,
    match(matching Criteria),
    project("_id", ...),
    sort(Direction.ASC, "_id"),
    limit(pageSize));

List<RESULT_OBJECT> mappedResult = mongoTemplate.aggregate(agg, COLLECTION_NAME, RESULT_OBJECT.class).getMappedResults();

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.