简体   繁体   English

MongoDB:使用DBcollection find时对数据进行排序

[英]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.

相关问题 Java中的parallelScanning mongodb DBCollection时指定查询条件 - specify query conditions when parallelScanning mongodb DBCollection in Java 使用DBCollection.mapReduce更改MongoDB模式:虚假嵌套的“值”属性 - Using DBCollection.mapReduce to change MongoDB schema: spurious nested “value” attribute MongoDB Java API:com.mongodb.DBCollection.Save()和com.mongodb.DBCollection.Insert()之间的区别? - MongoDB Java API: Difference between com.mongodb.DBCollection.Save() and com.mongodb.DBCollection.Insert()? java com.mongodb.DBCollection 创建后台索引 - java com.mongodb.DBCollection create a background index 数据获取后的Mongodb排序 - Mongodb sorting after data fetch 使用 compareToIgnoreCase (JShell) 对文件流进行排序时“找不到符号” - 'Cannot find symbol' when sorting a stream of files using compareToIgnoreCase (JShell) 使用Spring Boot时来自mongodb的数据 - Data from mongodb when using Spring boot Mongodb Aggregation Framework对巨大数据进行排序 - Mongodb Aggregation Framework Sorting the huge data 使用find() - 使用投影方法,使用mongodb java驱动程序3.4检索数据 - retrieving data with mongodb java driver 3.4 using find()-method with projection 排序数组,并使用Java在MongoDB中选择字段 - Sorting array, and selecting field in MongoDB using Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM