Get sorted distinct values with MongoTemplate

Andrew Nepogoda :

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

Andrew Nepogoda :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147666&siteId=1