简体   繁体   中英

Sorting DBList using Collections.sort

I have a DBList that contains DBObjects from a cursor = coll.find() query. I have a field named timestamp inside each DBObject and I want to sort the DBList by . 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. I would really appreciate the help.

The unsorted list was formed using this :

      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 . 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 . The list must be sorted only after the query is done.

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. MongoDB can support very complicated queries.

Strill, I think a better way is letting mongoDB sort it for you. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM