简体   繁体   English

使用 Panache 和 Quarkus 对 MongoDB 文档进行排序

[英]Sort MongoDB document using Panache and Quarkus

I am trying to sort MongoDb document by date created in descending order.我正在尝试按按降序创建的日期对 MongoDb 文档进行排序。 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我正在使用 quarkus 和 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您需要做的是通过 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