Get sorted distinct values with MongoTemplate

风流意气都作罢 提交于 2020-06-27 19:36:09

问题


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


回答1:


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.




回答2:


With Mongo Aggregation you can

db.getCollection('assignments').aggregate([
    {$group: {_id: "$fieldname"}},
    {$sort : {"_id" :1}}
    ])


来源:https://stackoverflow.com/questions/54791594/get-sorted-distinct-values-with-mongotemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!