Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
wuchang Avatar asked Jan 03 '14 04:01

wuchang


People also ask

Does MongoDB support sorting?

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.

How do I limit in MongoDB?

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.

How does sort work in MongoDB?

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)


1 Answers

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

like image 157
pulu Avatar answered Oct 11 '22 17:10

pulu