Spring Data Mongo - Query methods and Distinct field
Solution 1
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
.
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
Solution 2
in SpringBoot2 you can do the following :
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;
Brice Argenson
Updated on June 27, 2022Comments
-
Brice Argenson almost 2 years
I'm currently working on a project using Spring Data Mongo. My repository is just an interface extending 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. 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...
Did I do something wrong? What's the best way to solve get the distinct values of a field using Spring Data?
Thanks!
-
Brice Argenson about 8 yearsThanks for your answer. I was expecting something like that. Any idea of what the findDistinctBy described in the reference guide does?
-
Sigrist about 8 yearsThe keyword distinct is not supported in mongo repositories, check the supported keywords here docs.spring.io/spring-data/data-document/docs/current/reference/…
-
PAA about 5 yearsI am not clear with your answer. Could you please post complete solution?
-
PAA about 5 yearsCould you please guide here: stackoverflow.com/questions/55535331/… ?
-
Karthikeyan over 4 years@PAA Both pretty same, except the above example uses an iterator to support scalability- which is advisable. Let me know if you still have any question