java mongodb sort() 和 limit() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20896586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java mongodb sort() and limit() function
提问by wuchang
I want to sort the returned result for each JSP page(100 items each page),not a global sort.
我想对每个 JSP 页面的返回结果进行排序(每页 100 项),而不是全局排序。
DBObject sort = new BasicDBObject();
DBObject exist = new BasicDBObject();
DBObject query= new BasicDBObject();
exist.put("$exists",1);
query.put("sortKey":exist);//sortKey is not indexed
sort.put("sortKey",1);
DBCursor cursor = dbcollection.find(query).limit(100).sort(sort);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
But in fact ,the sort is stilled processed for all the documents in the collection,namely ,it is a global sort even though I use function limit(100) .Since the collection is very large-scale , the sort function will take quite a long time.So , I wonder if mongodb java driver has a feature which will perform a local(just sort for the returned 100 documents) instead of global sort?
但实际上,排序是对集合中的所有文档进行静止处理的,即,即使我使用函数 limit(100) 也是全局排序。由于集合非常大,排序函数将花费相当长的时间很长一段时间。所以,我想知道 mongodb java 驱动程序是否具有执行本地(仅对返回的 100 个文档进行排序)而不是全局排序的功能?
回答by Eve Freeman
There's no way to sort locally in the Java driver. If you want a local sort, read the documents into an array and sort the array.
无法在 Java 驱动程序中进行本地排序。如果需要局部排序,请将文档读入数组并对数组进行排序。
回答by pulu
By using Mongodb 3.x and the corresponding java driver, you sort by doing the following:
通过使用 Mongodb 3.x 和相应的 java 驱动程序,您可以通过执行以下操作进行排序:
List<Document> list = collection.find().sort(descending("number")).into(new ArrayList<Document>());
Usage sort as: sort(order("field"));
用法 sort as: sort(order("field"));
order = ascending or descending
顺序 = 升序或降序