45

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
  • 746
  • 1
  • 10
  • 23
İlker Korkut
  • 3,049
  • 3
  • 28
  • 49

10 Answers10

38

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

new Sort(new Order(Direction.ASC, FIELD_NAME).ignoreCase()
dev
  • 2,869
  • 5
  • 34
  • 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
  • 9
    This is deprecated now. Use Sort.by(Sort.Direction.ASC, FIELD_NAME)) instead – visrahane Apr 03 '19 at 05:54
16

NEW ANSWER - Spring Data Moore

Use Sort.by

Query().addCriteria(Criteria.where("field").`is`(value)).with(Sort.by(Sort.Direction.DESC, "sortField"))
Ronny Shibley
  • 1,862
  • 20
  • 25
15

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

imbond
  • 1,910
  • 1
  • 18
  • 21
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
  • 26,923
  • 21
  • 73
  • 125
Pravin Bansal
  • 3,455
  • 1
  • 24
  • 17
  • 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
5

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

This one worked for me:

query.with(Sort.by(Sort.Order.asc("pdate")));
Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Pooja Joshi
  • 666
  • 3
  • 3
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,113
  • 23
  • 23
0

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,395
  • 9
  • 45
  • 64
0

You can use Aggregation in repository

Repository

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