Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoTemplate method or query for finding maximum values from a fileds

Tags:

spring

mongodb

I am using MongoTemplate for my DB operations. Now i want to fetch the maximum fields values from the selected result. Can someone guide me how i write the query so that when i pass the query to find method it will return me the desired maximum fields of document . Thanks in advance Regards

like image 285
Waqas Ahmed Avatar asked Jan 31 '26 20:01

Waqas Ahmed


1 Answers

You can find "the object with the maximum field value" in spring-data-mongodb. Mongo will optimize sort/limit combinations IF the sort field is indexed (or the @Id field). Otherwise it is still pretty good because it will use a top-k algorithm and avoid the global sort (mongodb sort doc). This is from Mkyong's example but I do the sort first and set the limit to one second.

Query query = new Query();
query.with(new Sort(Sort.Direction.DESC, "idField"));
query.limit(1);
MyObject maxObject = mongoTemplate.findOne(query, MyObject.class);
like image 187
Wheezil Avatar answered Feb 03 '26 09:02

Wheezil