簡體   English   中英

使用Collections.sort對DBList進行排序

[英]Sorting DBList using Collections.sort

我有一個DBList包含DBObjectscursor = coll.find()查詢。 我在每個DBObject都有一個名為timestamp的字段,我想按最新的timestampDBList進行排序。 我知道我可以在這里使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM