簡體   English   中英

使用 Panache 和 Quarkus 對 MongoDB 文檔進行排序

[英]Sort MongoDB document using Panache and Quarkus

我正在嘗試按按降序創建的日期對 MongoDb 文檔進行排序。 我正在使用華麗,也在分頁。

我已經能夠正確地對每個單獨頁面中的數據進行排序,因為一旦我從集合中檢索到數據就會對數據進行排序。 但是第一頁中的數據是最舊的,而最后一頁中的數據是最新的。 任何人都知道如何在分頁時進行排序。 我正在使用 quarkus 和 Java

這是我目前的做法

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

在這里,您按頁面查詢集合,然后對每個頁面進行排序。 因此,結果將按集合插入順序發送,然后逐頁排序。

您需要做的是通過 MongoDB 排序對查詢進行排序,因為您使用的是Document而不是基於字符串的查詢,您可以在 Document 查詢上添加排序,或者您可以使用 Panache 排序功能: https://quarkus .io/guides/mongodb-panache#sorting

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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