[英]Spring Data Mongo - Query methods and Distinct field
I'm currently working on a project using Spring Data Mongo. 我目前正在使用Spring Data Mongo进行项目。 My repository is just an interface extending MongoRepository.
我的存储库只是扩展MongoRepository的接口。 I would like to add a custom query method in order to retrieve all distinct values for one of my collection's fields.
我想添加一个自定义查询方法,以检索集合中一个字段的所有不同值。
I tried something like this: 我尝试过这样的事情:
@RepositoryRestResource(path = "devices", collectionResourceRel = "deviceInfos")
public interface DeviceInfoRepository extends MongoRepository<DeviceInfo, String> {
@RestResource(path = "distinctUnitIds")
List<String> findDistinctUnitIdBy();
}
With that code, Spring give me an error because it's not able to build my list. 有了这些代码,Spring会给我一个错误,因为它无法建立我的列表。 So I tried this:
所以我尝试了这个:
@RepositoryRestResource(path = "devices", collectionResourceRel = "deviceInfos")
public interface DeviceInfoRepository extends MongoRepository<DeviceInfo, String> {
@RestResource(path = "distinctUnitIds")
List<DeviceInfo> findDistinctUnitIdBy();
}
That code works but the distinct seems to be totally ignored. 该代码可以工作,但独特之处似乎被完全忽略了。
The documentation about Distinct in query method is really not clear... 关于Distinct查询方法的文档确实不清楚...
Did I do something wrong? 我做错什么了吗? What's the best way to solve get the distinct values of a field using Spring Data?
解决使用Spring Data获得字段的不同值的最佳方法是什么?
Thanks! 谢谢!
You will have to use Spring Data MongoTemplate
- the MongoRepository
interfaces are made only for basic functionality and for more fine grain control of what you are querying, its best to use MongoTemplate
. 您将必须使用Spring Data
MongoTemplate
- MongoRepository
接口仅用于基本功能,并且为了更精细地控制您要查询的内容,最好使用MongoTemplate
。
Here is an example of how one would get distinct values from a collection: 这是一个如何从集合中获得不同值的示例:
Criteria criteria = new Criteria();
criteria.where("dataset").is("d1");
Query query = new Query();
query.addCriteria(criteria);
List list = mongoTemplate.getCollection("collectionName")
.distinct("source",query.getQueryObject());
Here is the link to more info: mongodb mongoTemplate get distinct field with some criteria 这是更多信息的链接: mongodb mongoTemplate通过某些条件获取不同的字段
in SpringBoot2 you can do the following : 在SpringBoot2中,您可以执行以下操作:
DistinctIterable<String> iterable = mongoTemplate.getCollection(COLLECTION_NAME).distinct("source",in(FieldValue,query.getQueryObject(), String.class);
MongoCursor<String> cursor = iterable.iterator();
List<String> list = new ArrayList<>();
while (cursor.hasNext()) {
list.add(cursor.next());
}
return list;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.