简体   繁体   中英

Sort MongoDB document using Panache and Quarkus

I am trying to sort MongoDb document by date created in descending order. I am using panache and am also paging.

I have been able to sort the data in each individual page correctly, since am sorting the data once I have retrieved it from the collection. However the data in the first page is the oldest while that in the last page is the newest. Anyone have a clue on how to approach sorting when paging. I am using quarkus and Java

Here is how I do it currently

PanacheQuery<BasicInfo> basicInfoPanacheQuery;

// is used to sort by createdDate
Comparator<BasicInfo> byDateCreated = (c1, c2) -> {
      if (c1.getCreatedDate().isAfter(c2.getCreatedDate())) return -1;
      else return 1;
    };

Bson searchBson = Filters.and(Filters.eq("entity", 2));

Document bsonDocument = bsonToDocument(searchBson.toBsonDocument(BsonDocument.class,
        MongoClientSettings.getDefaultCodecRegistry()));

basicInfoPanacheQuery = BasicInfo.find(bsonDocument).page(Page.of(page, PAGE_SIZE));
    
basicInfoPanacheQuery
        .stream()
        .sorted(byDateCreated)
        .forEach(
            x -> {
              // manipulate the data
            }
        );

Here you query the collection by page then sort each page. So the results will be send on the collection insertion order, then sorted page by page.

What you need to do is to sort the query via a MongoDB sort, as you use a Document and not a string based query, you can add a sort on the Document query, or you can use Panache sorting capability: https://quarkus.io/guides/mongodb-panache#sorting

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