2016-10-23 46 views
0

我有一個DBList,其中包含DBObjects來自cursor = coll.find()查詢。我在DBObject內部有一個名爲timestamp的字段,我想用最新的時間戳DBList進行排序。我知道我可以在這裏使用Collections.sort(),但對於mongoDB的java API來說是新手,我似乎無法根據特定字段進行排序。我真的很感謝幫助。使用Collections.sort排序DBList

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。在查詢完成後,list必須僅排序

回答

0

問題是,你如何改變你的查詢。你能告訴我你在for循環中改變你的查詢的代碼,我想我可以爲你提供一個更好的查詢。 MongoDB可以支持非常複雜的查詢。

Strill,我認爲一個更好的方法是讓mongoDB爲你排序。 你可以像寫:

coll.find(whereQueryModified).sort(new BasicDBObject("timestamp",-1)); 

如果您不能使用排序方法,您可能需要使用MongoDB的驅動程序的更新版本。

此外,「時間戳」是對於對象的關鍵字的長度。 mongoDB非常耗費空間,因爲mongoDB將每個鍵和值存儲在磁盤中。

0

您可以更改查詢如下策略:

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

如果DBList工具List

Collections.sort(unsortedList, Comparator.comparing(DBObject::getTimestamp).reversed());

相關問題