49

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?

noob
  • 774
  • 1
  • 10
  • 23
İlker Korkut
  • 3,129
  • 3
  • 30
  • 51

11 Answers11

44

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

new Sort(new Order(Direction.ASC, FIELD_NAME).ignoreCase()
dev
  • 2,949
  • 5
  • 37
  • 48
  • thanks , that was what I mean years ago in my answer, I'm accepting your answer. – İlker Korkut Dec 11 '15 at 22:47
  • You can actually pass a comma delimited list (or pre-constructed List) to the Sort constructor and define multiple ordering criteria! – th3morg Sep 16 '16 at 14:43
  • 2
    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! – Oleksandr Yefymov Sep 14 '17 at 22:23
  • 11
    This is deprecated now. Use Sort.by(Sort.Direction.ASC, FIELD_NAME)) instead – visrahane Apr 03 '19 at 05:54
22

NEW ANSWER - Spring Data Moore

Use Sort.by

Query().addCriteria(Criteria.where("field").`is`(value)).with(Sort.by(Sort.Direction.DESC, "sortField"))
Ronny Shibley
  • 2,030
  • 22
  • 25
17

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! :)

RubioRic
  • 2,442
  • 4
  • 28
  • 35
imbond
  • 2,030
  • 1
  • 20
  • 22
7

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<>.

Gene
  • 10,819
  • 1
  • 66
  • 58
  • Please provide an explanation with your code. Codes without any explanation are going to be deleted. – QuentinC Apr 24 '21 at 04:59
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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Pravin Bansal
  • 4,315
  • 1
  • 28
  • 19
  • 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")); – ALI Sep 20 '20 at 11:14
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);
Jijesh Kumar
  • 299
  • 2
  • 13
4

This one worked for me:

query.with(Sort.by(Sort.Order.asc("pdate")));
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Pooja Joshi
  • 1,418
  • 1
  • 4
  • 6
1

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);
Leonel Sanches da Silva
  • 6,972
  • 9
  • 46
  • 66
1

You can use Aggregation in repository

Repository

  @Aggregation(pipeline ={
    "{$match: { id : ?0 }",
    "{$sort: {date: 1}}",
    "{$limit: 1}"
  }
  Optional<Student> findStudent(String id);
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();
Hany Sakr
  • 2,591
  • 28
  • 27
0

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

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