[英]Sorting DBList using Collections.sort
I have a DBList
that contains DBObjects
from a cursor = coll.find()
query. 我有一个DBList
包含DBObjects
从cursor = coll.find()
查询。 I have a field named timestamp
inside each DBObject
and I want to sort the DBList
by latest timestamp . 我在每个DBObject
都有一个名为timestamp
的字段,我想按最新的timestamp对DBList
进行排序。 I know I can use Collections.sort()
here but being new to mongoDB's java API, I can't seem to be able to sort based on a specific field. 我知道我可以在这里使用Collections.sort()
,但是对于mongoDB的java API来说是新手,我似乎无法根据特定字段进行排序。 I would really appreciate the help. 我非常感谢您的帮助。
The unsorted list
was formed using this : unsorted list
是使用以下形式形成的:
DBCursor cursor = coll.find(whereQuery);
while(cursor.hasNext()) {
DBObject o = cursor.next();
System.out.println(o.toString());
unsortedList.add(o);
}
After this, I want to sort unsortedList
in the descending order of timestamp
. 此后,我想按timestamp
的降序对unsortedList
进行排序。 I'm quite unclear on how to do this and thanks in advance for the help. 我不清楚如何执行此操作,在此先感谢您的帮助。
Also solutions, such as coll.find().sort(timestamp,-1)
can't be used because there is an outer for
loop which keeps changing the whereQuery
. 同样,不能使用诸如coll.find().sort(timestamp,-1)
解决方案,因为存在一个外部for
循环,该循环不断更改whereQuery
。 The list
must be sorted only after the query is done. 仅在查询完成后才能对list
进行排序。
The problem is that how do you change your query. 问题是您如何更改查询。 Could you show me the code that you change your query in the for loop, I think i can provide a better query for you. 您能告诉我您在for循环中更改查询的代码,我想我可以为您提供更好的查询。 MongoDB can support very complicated queries. MongoDB可以支持非常复杂的查询。
Strill, I think a better way is letting mongoDB sort it for you. rill,我认为一种更好的方法是让mongoDB为您排序。 You can write like: 您可以这样写:
coll.find(whereQueryModified).sort(new BasicDBObject("timestamp",-1));
If you cannot use the sort method, you might need to use a newer version of mongoDB driver. 如果无法使用sort方法,则可能需要使用更新版本的mongoDB驱动程序。
Besides, "timestamp" is to long for a key of an object. 此外,“时间戳记”对于对象的键很长。 It's very space exhausting for mongoDB because mongoDB store every key and value in disk. 对于mongoDB来说,这非常浪费空间,因为mongoDB将每个键和值存储在磁盘中。
You can change the query as following strategy: 您可以按照以下策略更改查询:
List<DBObject> pipeline=new ArrayList<DBObject>();
DBObject match = new BasicDBObject("$match", new BasicDBObject("date", sdf.format(new Date())).append("country", country));
DBObject unwind = new BasicDBObject("$unwind", "$details");
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("details.datetime", -1));
DBObject limit = new BasicDBObject("$limit", 1);
pipeline.add(match);
pipeline.add(unwind);
pipeline.add(sort);
pipeline.add(limit);
AggregationOutput outputoutput = collection.aggregate(pipeline);
如果DBList
实现List
:
Collections.sort(unsortedList, Comparator.comparing(DBObject::getTimestamp).reversed());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.