Sort documents in collections while fetching

泄露秘密 提交于 2019-12-20 02:29:16

问题


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" }

At Java code,I list them as follows:

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

How could I fetch these documents sorted by ID !


回答1:


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;

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.




回答2:


Should be something like this:

 MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
  List<Resource> resourceList = mongoOperations.findAll(Resource.class).sort({'_id' : 1});
  return resourceList;

You need to append .sort({'_id' : 1}) for ascending order or .sort({'_id' : -1}) for descending order.


For Java:

.sort( new BasicDBObject( "_id" , 1 ) )

Solution from echo:

DBCursor dbCursor = mongoOperations.getCollection(RESOURCE_COLLECTION_NAME).find().sort(new BasicDBObject("_id", 1)); 
List<DBObject> dbObjects = dbCursor.toArray(); 
List<Map> items = new ArrayList<Map>(dbCursor.length()); 
for (DBObject dbObject : dbObjects) { 
 Map map = dbObject.toMap(); 
 items.add(dbObject.toMap()); 
}


来源:https://stackoverflow.com/questions/13895876/sort-documents-in-collections-while-fetching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!