quma
quma

Reputation: 5733

Spring data get unique values of group by

I have the following records in my MongoDB database and I will get only the years. e.g. if I have:

ID   year ...
1   "2016" ...
2   "2016" ...
3   "2017" ...
4   "2016" ...
5   "2018" ...

then I will get:

2016
2017
2018

as result. Is this somehow possible with Spring Data with method name (I havn't seen GroupBy for methods) or with @Query.

Upvotes: 1

Views: 780

Answers (1)

chridam
chridam

Reputation: 103335

You can issue the distinct() command to get the desired result. In mongo shell, run the following:

db.collection.distinct("year")

In SpringData, you need to use the @Autowired annotation to bring in the base MongoTemplate from spring-data-mongodb

@Autowired
MongoTemplate mongoTemplate;

You can then use the mongoTemplate instance to query the underlying collection as

List<String> coll = mongoTemplate.getCollection("collectionName").distinct("year");

Upvotes: 2

Related Questions