简体   繁体   中英

MongoDB : Sorting Data when using DBcollection find

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM