Brice Argenson
Brice Argenson

Reputation: 832

Spring Data Mongo - Query methods and Distinct field

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!

Upvotes: 5

Views: 18774

Answers (2)

Karthikeyan
Karthikeyan

Reputation: 2724

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;

Upvotes: 2

Simon
Simon

Reputation: 19928

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

Upvotes: 7

Related Questions