8

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

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.