MongoDB 文档的最大值/最小值 [英] Max / min values with MongoDB document

查看:53
本文介绍了MongoDB 文档的最大值/最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Data 访问 MongoDB 数据库.如何使用 MongoTemplate 类检索其字段之一中具有最大值的最大文档.谢谢!

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!

推荐答案

Rinku 的答案是正确的,但不是 Spring.您可以在 spring-data-mongodb 中执行此操作.如果排序字段被索引(或@Id 字段),Mongo 将优化排序/限制组合.否则它仍然很不错,因为它将使用 top-k 算法并避免全局排序(mongodb 排序文档).这是来自 Mkyong 的例子 但我先进行排序并将限制设置为一秒.

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

这篇关于MongoDB 文档的最大值/最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆