【问题标题】:Sort MongoDB document using Panache and Quarkus使用 Panache 和 Quarkus 对 MongoDB 文档进行排序
【发布时间】:2021-06-08 17:36:14
【问题描述】:

我正在尝试按按降序创建的日期对 MongoDb 文档进行排序。我正在使用 panache 并且也在分页。

我已经能够正确地对每个单独页面中的数据进行排序,因为一旦我从集合中检索到数据就会对数据进行排序。但是第一页中的数据是最旧的,而最后一页中的数据是最新的。任何人都知道如何在分页时进行排序。我正在使用 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
            }
        );

【问题讨论】:

    标签: java mongodb quarkus quarkus-panache


    【解决方案1】:

    在这里您按页面查询集合,然后对每个页面进行排序。因此结果将按集合插入顺序发送,然后逐页排序。

    您需要做的是通过 MongoDB 排序对查询进行排序,因为您使用 Document 而不是基于字符串的查询,您可以在 Document 查询上添加排序,或者您可以使用 Panache 排序功能: https://quarkus.io/guides/mongodb-panache#sorting

    【讨论】:

      猜你喜欢
      • 2023-02-19
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多