[英]Sorting DBList using Collections.sort
我有一個DBList
包含DBObjects
從cursor = coll.find()
查詢。 我在每個DBObject
都有一個名為timestamp
的字段,我想按最新的timestamp對DBList
進行排序。 我知道我可以在這里使用Collections.sort()
,但是對於mongoDB的java API來說是新手,我似乎無法根據特定字段進行排序。 我非常感謝您的幫助。
unsorted list
是使用以下形式形成的:
DBCursor cursor = coll.find(whereQuery);
while(cursor.hasNext()) {
DBObject o = cursor.next();
System.out.println(o.toString());
unsortedList.add(o);
}
此后,我想按timestamp
的降序對unsortedList
進行排序。 我不清楚如何執行此操作,在此先感謝您的幫助。
同樣,不能使用諸如coll.find().sort(timestamp,-1)
解決方案,因為存在一個外部for
循環,該循環不斷更改whereQuery
。 the query is done. 僅查詢完成才能對list
進行排序。
問題是您如何更改查詢。 您能告訴我您在for循環中更改查詢的代碼,我想我可以為您提供更好的查詢。 MongoDB可以支持非常復雜的查詢。
rill,我認為一種更好的方法是讓mongoDB為您排序。 您可以這樣寫:
coll.find(whereQueryModified).sort(new BasicDBObject("timestamp",-1));
如果無法使用sort方法,則可能需要使用更新版本的mongoDB驅動程序。
此外,“時間戳記”對於對象的鍵很長。 對於mongoDB來說,這非常浪費空間,因為mongoDB將每個鍵和值存儲在磁盤中。
您可以按照以下策略更改查詢:
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.