MongoDB: sort data using DBcollection search

I want to return the results of a search query using sorting based on the 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 for working with any ideas?

+6
source share
1 answer

If you look at the Java driver APIs, the find method expects two parameters: the request and the fields to be returned,

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

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

Remember that a DBCursor object performs lazy fetching into a database, so you can use sorting, limiting, or skipping without overhead.

+8
source

All Articles