Jonathan Luke
Jonathan Luke

Reputation: 86

Spring - Sort Aggregation

I have an aggregation similar to this one:

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

I would like to be able to sort it with variable data (sortField and Sort), but I don't know how to add it to the aggregation. To get an idea I would like something like:

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

Does anyone have any idea how to do it?

Upvotes: 2

Views: 2192

Answers (1)

Lucas Declercq
Lucas Declercq

Reputation: 1730

Aggregation.newAggregation() can take a list of AggregationOperation.

You could do something like this :

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

Upvotes: 2

Related Questions