AKKI
AKKI

Reputation: 121

Get maximum value for column in mongoDB

How to get maximum value for column in mongoDB using mongoTemplate object in spring

Upvotes: 2

Views: 1058

Answers (2)

Wheezil
Wheezil

Reputation: 3462

Abhishek's answer doesn't address Spring and how to do this in MongoTemplate.

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);

Upvotes: 0

Abhishek Kumar
Abhishek Kumar

Reputation: 3366

I am guessing you are not talking about query syntex. If you are talking about writing performant query, then you can choose to have index on that field.

ensureIndex({ coll-name : 1 })

Query

db.coll.find({}, {coll-name : 1, _id : 0}).sort({ coll-name : -1 }).limit(1)

This will return you a json having max-value for coll-name.

Upvotes: 1

Related Questions