Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring Data Mongodb, is it possible to get the max value of a field without pulling and iterating over an entire collection?

Using mongoTemplate.find(), I specify a Query with which I can call .limit() or .sort():

.limit() returns a Query object
.sort() returns a Sort object

Given this, I can say Query().limit(int).sort(), but this does not perform the desired operation, it merely sorts a limited result set.

I cannot call Query().sort().limit(int) either since .sort() returns a Sort()

So using Spring Data, how do I perform the following as shown in the mongoDB shell? Maybe there's a way to pass a raw query that I haven't found yet?

I would be ok with extending the Paging interface if need be...just doesn't seem to help any. Thanks!

> j = { order: 1 }
{ "order" : 1 }
> k = { order: 2 }
{ "order" : 2 }
> l = { order: 3 }
{ "order" : 3 }
> db.test.save(j)
> db.test.save(k)
> db.test.save(l)
> db.test.find()
{ "_id" : ObjectId("4f74d35b6f54e1f1c5850f19"), "order" : 1 }
{ "_id" : ObjectId("4f74d3606f54e1f1c5850f1a"), "order" : 2 }
{ "_id" : ObjectId("4f74d3666f54e1f1c5850f1b"), "order" : 3 }
> db.test.find().sort({ order : -1 }).limit(1)
{ "_id" : ObjectId("4f74d3666f54e1f1c5850f1b"), "order" : 3 }
like image 283
jeremy.ary Avatar asked Mar 29 '12 21:03

jeremy.ary


People also ask

What is the limit of in query MongoDB?

In MongoDB, the limit() method limits the number of records or documents that you want. It basically defines the max limit of records/documents that you want. Or in other words, this method uses on cursor to specify the maximum number of documents/ records the cursor will return.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Can we use spring data JPA with MongoDB?

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


1 Answers

You can do this in sping-data-mongodb. Mongo will optimize sort/limit combinations IF the sort field is indexed (or the @Id field). This produces very fast O(logN) or better results. Otherwise it is still O(N) as opposed to O(N*logN) 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 109
Wheezil Avatar answered Oct 25 '22 00:10

Wheezil