【问题标题】:Sorting DBList using Collections.sort使用 Collections.sort 对 DBList 进行排序
【发布时间】:2017-03-05 15:19:42
【问题描述】:

我有一个DBList,其中包含来自cursor = coll.find() 查询的DBObjects。我在每个DBObject 中有一个名为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 循环会不断更改whereQuerylist 必须仅在查询完成后 进行排序

【问题讨论】:

    标签: java mongodb sorting collections


    【解决方案1】:

    问题在于如何更改查询。您能否向我展示您在 for 循环中更改查询的代码,我想我可以为您提供更好的查询。 MongoDB 可以支持非常复杂的查询。

    Srill,我认为更好的方法是让 mongoDB 为您排序。 你可以这样写:

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

    如果您不能使用排序方法,则可能需要使用较新版本的 mongoDB 驱动程序。

    此外,“时间戳”是一个对象的键长。这对 mongoDB 来说非常消耗空间,因为 mongoDB 将每个键和值都存储在磁盘中。

    【讨论】:

      【解决方案2】:

      您可以按照以下策略更改查询:

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

      【讨论】:

        【解决方案3】:

        如果DBList 实现List

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-03
          • 1970-01-01
          • 2012-07-15
          • 1970-01-01
          • 1970-01-01
          • 2013-10-04
          • 1970-01-01
          • 2018-05-10
          相关资源
          最近更新 更多