Max / min values with MongoDB document

2019-07-31 16:39发布

问题:

I am using Spring Data to access MongoDB database. How can I retrieve max a document with max value in one of its fields, using MongoTemplate class. Thanks!

回答1:

use a combination of sort and limit to emulate min and max:

db.test.insert({a: 1})
db.test.insert({a: 2})
db.test.insert({a: 3})
db.test.find().sort({a: 1}).limit(1)
db.test.find().sort({a: -1}).limit(1)
sort({a: 1}) is an ascending (minimum-first) sort on the a field, and then only return the first document, which will be the minimum value for that field.
sort({a: -1}) is an descending (maximum-first) sort on the a field, and then only return the first document, which will be the maximum value for that field.



回答2:

Rinku's answer is correct but not Spring. You can do this 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);