Search code examples
mongodbspring-data

Distinct in Spring Data MongoDB


Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how should I include the distinct flag?

Link to the Spring Data Mongo example -- Example 4.4. Query creation from method names

// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

Solution

  • Lot has changed since this question was posted. Answering my own question as this question keeps popping up.

    Support is there since 3.0 and higher

    public DistinctIterable<String> getUniqueTask() {
        return mongoTemplate.getCollection(TABLE).distinct("FIELD", String.class);
    }
    

    Side Note: You can even add filters/regex to this query. Read docs. If you cannot find, ping, will post the answer.