Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : Sorting Data when using DBcollection find

Tags:

java

mongodb

I want to return the results from the find query with the help of sortaing based on lastUpdated field .

Currently i have seen two ways

First Approach

BasicDBObject query = new BasicDBObject();
query.put("updated_at","-1");
query.put(MONGO_ATTR_SYMBOL, "" + symbol);
DBCursor cursor = DBcollection.find(query).sort(query);

Second Approach

DBCursor cursor = DBcollection.find(query,new BasicDBObject("sort", new BasicDBObject("lastUpdated ", -1)));

What is the best option to work with any ideas ??

like image 373
Pawan Avatar asked Dec 18 '12 06:12

Pawan


1 Answers

If you take a look at Java Driver API, the method find expects two parameters, the query and the fields that will be returned.

Once you want to sort the results, use the traditional find method and sort the DBCursor.

DBCursor cursor = DBCollection.find(query);
cursor.sort(new BasicDBObject("lastUpdated ", -1));

Remember, the DBCursor object do a lazy fetch to database, so you can use sort, limit or skip without overheads.

like image 147
Miguel Cartagena Avatar answered Oct 26 '22 08:10

Miguel Cartagena