Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sorted distinct values with MongoTemplate

I am trying to get list of sorted distinct fields:

public List<Object> getDistinctValues(String collection, String fieldName) {
    Query query = new Query();
    query.with(new Sort(Sort.Direction.ASC, fieldName));
    return mongoTemplate.findDistinct(query, fieldName, collection, Object.class);
}

but sorting isn't applied. Is there any way to do it with mongoTemplate?

spring-boot-starter-data-mongodb: 2.1.2.RELEASE

like image 419
Andrew Nepogoda Avatar asked Dec 13 '25 04:12

Andrew Nepogoda


1 Answers

Based on previous answer I solved my problem with Mongo Aggregation:

@Override
public List<Object> getDistinctValues(String collection, String fieldName, Sort.Direction sort) {
    Aggregation agg = Aggregation.newAggregation(
            Aggregation.group(fieldName),
            Aggregation.sort(sort, "_id")
    );
    return mongoTemplate.aggregate(agg, collection, Document.class)
            .getMappedResults()
            .stream()
            .map(item -> item.get("_id"))
            .collect(Collectors.toList());
}

I hope it will be helpful for somebody.

like image 99
Andrew Nepogoda Avatar answered Dec 15 '25 16:12

Andrew Nepogoda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!