Spring数据获得group by的唯一值

时间:2016-01-20 13:33:09

标签: mongodb spring-data

我在MongoDB数据库中有以下记录,我只会得到这些年份。例如如果我有:

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

然后我会得到:

2016
2017
2018

结果。使用方法名称的Spring Data(我没有看到方法的GroupBy)或者使用@Query,这在某种程度上是可能的。

1 个答案:

答案 0 :(得分:2)

您可以发出 distinct() 命令以获得所需的结果。在mongo shell中,运行以下命令:

db.collection.distinct("year")

在SpringData中,您需要使用@Autowired注释从spring-data-mongodb引入基础MongoTemplate

@Autowired
MongoTemplate mongoTemplate;

然后,您可以使用mongoTemplate实例查询基础集合

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