Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MongoDB query sorting

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?

like image 216
İlker Korkut Avatar asked Aug 29 '13 21:08

İlker Korkut


People also ask

Can we use JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.


3 Answers

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

new Sort(new Order(Direction.ASC, FIELD_NAME).ignoreCase()
like image 149
dev Avatar answered Oct 17 '22 09:10

dev


NEW ANSWER - Spring Data Moore

Use Sort.by

Query().addCriteria(Criteria.where("field").`is`(value)).with(Sort.by(Sort.Direction.DESC, "sortField"))
like image 19
Ronny Shibley Avatar answered Oct 17 '22 10:10

Ronny Shibley


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

like image 15
imbond Avatar answered Oct 17 '22 09:10

imbond