使用Spring Data Mongodb,是否有可能在不提取和迭代整个集合的情况下获得字段的最大值? [英] Using Spring Data Mongodb, is it possible to get the max value of a field without pulling and iterating over an entire collection?
问题描述
使用mongoTemplate.find()
,我指定一个查询,可以通过它调用.limit()
或.sort()
:
Using mongoTemplate.find()
, I specify a Query with which I can call .limit()
or .sort()
:
.limit()
返回Query
对象
.sort()
返回一个Sort
对象
.limit()
returns a Query
object
.sort()
returns a Sort
object
鉴于此,我可以说Query().limit(int).sort(),但这不能执行所需的操作,它只是对有限的结果集进行排序.
Given this, I can say Query().limit(int).sort(), but this does not perform the desired operation, it merely sorts a limited result set.
由于.sort()返回Sort(),我无法调用Query().sort().limit(int)
I cannot call Query().sort().limit(int) either since .sort() returns a Sort()
因此,使用Spring Data,如何执行mongoDB shell中所示的以下操作?也许有一种方法可以传递我尚未找到的原始查询?
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?
如果需要的话,我可以扩展Paging接口...只是似乎无济于事.谢谢!
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 }
推荐答案
您可以在sping-data-mongodb中执行此操作.如果索引了排序字段(或@Id字段),则Mongo将优化排序/限制组合.这会产生非常快的O(logN)或更好的结果.否则,它仍然是O(N)而不是O(N * logN),因为它将使用top-k算法并避免使用全局排序( Mkyong的示例但我先进行排序,然后将限制设置为一秒.
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);
这篇关于使用Spring Data Mongodb,是否有可能在不提取和迭代整个集合的情况下获得字段的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!