Spring - 排序聚合

Spring - Sort Aggregation

我有一个类似于这个的聚合:

public Flux<Example> listWithFilters (int pageNumber, int size , String sortField, String sort, String userName) {
    
    Criteria criteria = new Criteria();
    criteria = criteria.where("orgId").is(orgId).and("category").all(category);
    criteria = criteria.orOperator(Criteria.where(DELETED).isNull(), Criteria.where(DELETED).is(false));

    AggregationExpression condition = ConditionalOperators.when(ArrayOperators.arrayOf(ConditionalOperators
                    .ifNull("favourite").then(Collections.emptyList())).containsValue(userName))
            .then(true)
            .otherwise(false);

    Pageable pageableRequest = PageRequest.of(pageNumber, size);
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())),
            Aggregation.limit(pageableRequest.getPageSize()),
            Aggregation.addFields().addField("isFav").withValue(condition).build());

    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );
    return Flux.just(Example);
}

我希望能够使用可变数据(sortField 和 Sort)对其进行排序,但我不知道如何将其添加到聚合中。为了得到一个想法,我想要这样的东西:

if(sort.equals("asc")){
Aggregation.sort(Sort.Direction.ASC, sortField));
}else{
Aggregation.sort(Sort.Direction.DESC, sortField));}

有人知道怎么做吗?

Aggregation.newAggregation()可以取AggregationOperation的列表。

你可以这样做:

    List<AggregationOperation> aggregationOperations = new ArrayList<>();
    aggregationOperations.add(Aggregation.match(criteria));
    aggregationOperations.add(Aggregation.skip((long) (pageableRequest.getPageNumber() * pageableRequest.getPageSize())));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.limit(pageableRequest.getPageSize()));
    aggregationOperations.add(Aggregation.addFields().addField("isFav").withValue(condition).build());

    if (sort.equals("asc")) {
        aggregationOperations.add(Aggregation.sort(Sort.Direction.ASC, sortField));
    }else{
        aggregationOperations.add(Aggregation.sort(Sort.Direction.DESC, sortField));
    }

    Aggregation aggregation = Aggregation.newAggregation(aggregationOperations);
    filterResponse.setListExample(
            mongo.aggregate(aggregation, mongo.getCollectionName(ExampleClass.class), ExampleClass.class).collectList().share().block()
    );