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 ??
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.
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