MongoDB : Sorting Data when using DBcollection find

时光总嘲笑我的痴心妄想 提交于 2021-02-16 06:36:48

问题


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:


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.



来源:https://stackoverflow.com/questions/13927867/mongodb-sorting-data-when-using-dbcollection-find

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!