Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom sorting query in spring boot for a mongo db repository?

I want to put this query with @Query annotation in my repository.

This is the query:

`db.report.find({'company' : 'Random'}).sort( { 'reportDate' : -1} ).limit(1)`

Which is the best way to implement custom queries with @Query annotations or to use MongoTemplate ?

like image 371
Gustavo Avatar asked Dec 19 '22 10:12

Gustavo


2 Answers

Using Mongo Template.

Criteria find = Criteria.where("company").is("Random");
Query query = new Query().addCriteria(find).with(new Sort(Sort.Direction.DESC, "reportDate"));
BasicDBObject result = mongoOperations.findOne(query, BasicDBObject.class, "collection_name");

Using Mongo Repository

Report findTopByCompanyOrderByReportDateDesc(String company)
like image 68
s7vr Avatar answered Dec 21 '22 00:12

s7vr


Note that in the new version of Springboot(v2.2.5), the correct method is sort.by(). like this:

Query query = new Query().addCriteria(find).with(Sort.by(Sort.Direction.DESC, "reportDate"));
like image 41
user13025703 Avatar answered Dec 20 '22 23:12

user13025703