繁体   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