MongoDB:使用 DBcollection find 时对数据进行排序 [英] MongoDB : Sorting Data when using DBcollection find

查看:77
本文介绍了MongoDB:使用 DBcollection find 时对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在基于 lastUpdated 字段的排序帮助下返回查找查询的结果.

I want to return the results from the find query with the help of sortaing based on lastUpdated field .

目前我看到了两种方式

第一种方法

BasicDBObject query = new BasicDBObject();
query.put("updated_at","-1");
query.put(MONGO_ATTR_SYMBOL, "" + symbol);
DBCursor cursor = DBcollection.find(query).sort(query);

第二种方法

DBCursor cursor = DBcollection.find(query,new BasicDBObject("sort", new BasicDBObject("lastUpdated ", -1)));

处理任何想法的最佳选择是什么??

What is the best option to work with any ideas ??

推荐答案

如果你看看 Java Driver API,方法 find 需要两个参数,查询和将返回的字段.

If you take a look at Java Driver API, the method find expects two parameters, the query and the fields that will be returned.

一旦您想对结果进行排序,请使用传统的 find 方法并对 DBCursor 进行排序.

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));

请记住,DBCursor 对象对数据库执行延迟获取,因此您可以使用排序、限制或跳过而不会产生开销.

Remember, the DBCursor object do a lazy fetch to database, so you can use sort, limit or skip without overheads.

这篇关于MongoDB:使用 DBcollection find 时对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆