[英]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 . 我想在查找基于lastUpdated字段的sortaing的帮助下返回查询结果。
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. 如果您查看Java Driver API,方法find需要两个参数,即查询和将返回的字段。
Once you want to sort the results, use the traditional find method and sort the DBCursor. 想要对结果进行排序后,请使用传统的find方法并对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. 请记住,DBCursor对象对数据库执行惰性提取,因此您可以使用排序,限制或跳过而无需开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.