简体   繁体   中英

java mongodb sort() and limit() function

I want to sort the returned result for each JSP page(100 items each page),not a global sort.

   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?

By using Mongodb 3.x and the corresponding java driver, you sort by doing the following:

List<Document> list = collection.find().sort(descending("number")).into(new ArrayList<Document>());

Usage sort as: sort(order("field"));

order = ascending or descending

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM