提取时对集合中的文档进行排序 [英] Sort documents in collections while fetching

查看:53
本文介绍了提取时对集合中的文档进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB上有一个名为resource的集合. 它具有以下文档:

I have a collection called at MongoDB called resource. It has the following documents:

{ "_id" : "Abb.e", "_class" : "Resource", "resourceEmail" : "test1@test.com" }
{ "_id" : "Dasd.tt", "_class" : "Resource","resourceEmail" : "test2@test.com" }
{ "_id" : "Bbb.rr", "_class" : "Resource", "resourceEmail" : "test3@test.com" }

在Java代码中,我将它们列出如下:

At Java code,I list them as follows:

 MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
  List<Resource> resourceList = mongoOperations.findAll(Resource.class);
  return resourceList;

如何获取按ID排序的这些文档!

How could I fetch these documents sorted by ID !

推荐答案

在使用Spring Data时,您可以使用Query对象查询集合中的所有文档并对结果进行排序.

As you're using Spring Data, you could use a Query object to query all documents in the colletion and sort the results.

MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
Query q = new Query().with(new Sort(Sort.Direction.ASC, "_id"));
List<Resource> resourceList = mongoOperations.find(q, Resource.class);
return resourceList;

当然,您可以迭代结果列表并对其进行手动排序,甚至可以使用Collection.sort方法,但是我认为,如果在用于排序的属性中有一个索引,则对mongodb sort进行排序会更快结果.

Of course that you could iterate the list of results and sort it manually, or even use Collection.sort method, but I think if you have an index in the property that you're using to sort, it's faster to mongodb sort the results.

这篇关于提取时对集合中的文档进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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