关于 Spring MVC with MongoDB:Spring MVC with MongoDB – Sorting and Limits | 珊瑚贝

Spring MVC with MongoDB – Sorting and Limits


在 Spring MVC 中对 MongoDB 查询结果进行排序的最佳方法是什么?我已经在 XML 文件中设置了所有映射,我可以在 Service 类中调用 myrepository.findAll() 就好了,它工作得很好。

我如何对这些结果进行排序(例如按日期)和/或限制结果(例如按 3 等)。在 Mongo 本身中,只需执行 db.mycollection.find().sort({ postedAt : -1}); 就很容易了。或者只是抛出一个 .limit(3) 来获得前 3 个结果。

在 Spring MVC 环境中处理此问题的最佳方法是什么?

谢谢。


如果你的 myrepository 对象是 MongoRepository 的一个实例,你可以使用 Pageable 对象作为参数调用 findAll 方法。

1
2
Pageable page = new PageRequest(0, 3, new Sort(Direction.DESC,”postedAt”));
myrepository.findAll(page);

其实这个方法来自PagingAndSortingRepository接口。


我觉得在 MongoDB 本身中排序很好,因为那里有很多选项,例如您提到的方式将给出排序列表。您可以定义一个索引,它也可以使排序更容易。那么在 spring 环境中显示应该是不费吹灰之力的。此外,如果您有分页类型的用例,那么正如您所说,您可以在 mongo 层进行限制,并将那么多记录带到 spring 环境中。


来源:https://www.codenong.com/13919279/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9364.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?