问题
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