mongodbspring-webfluxspring-data-mongodb-reactive

Spring MongoDB Reactive: Sorting query and aggregation does not sort results


In short - i try to retrieve a sorted list of objects using both find with Query object and aggregation object.

But... no luck - randomly ordered lists every time.

I tried two options:

@Component
@RequiredArgsConstructor
public class EventFilteredRepository {
    private final ReactiveMongoTemplate mongoTemplate;

    public Flux<Event> findEventsByCriteriaSortedByHostRating(Criteria criteria){
        return mongoTemplate.aggregate(Aggregation.newAggregation(Aggregation.match(criteria),
            Aggregation.sort(Sort.by(Sort.Direction.DESC,"hostRating"))), "Event", Event.class);
    }
}

And this:

@Component
@RequiredArgsConstructor
public class EventFilteredRepository {
    private final ReactiveMongoTemplate mongoTemplate;

    public Flux<Event> findEventsByCriteriaSortedByHostRating(Criteria criteria){
        return mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("hostRating"))), Event.class);
    }
}

The only way i can make it work is:

@Component
@RequiredArgsConstructor
public class EventFilteredRepository {
    private final ReactiveMongoTemplate mongoTemplate;

    public Flux<Event> findEventsByCriteriaSortedByHostRating(Criteria criteria){
        return mongoTemplate.find(Query.query(criteria), Event.class).sort(Comparator.comparingDouble(Event::getHostRating).reversed());
    }
}

But this way i assume it does it all in-memory pulling all the cursor and then sorting it. This could be a big issue on a big amount of data.

Please, help or advise anything! Thank you so much in advance!


Solution

  • I found actually the problem.

    I was using the results in a flatMap which doesn't preserve order.

    One needs to use either concatMap or flatMapSequential for sorted lists.