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?
MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted.
To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.
This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field. When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest: MinKey (internal type)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With