Reputation: 175
Consider the following dependency:
org.springframework.boot.spring-boot-starter-data-mongodb-reactive
(2.0.2.RELEASE)I'm having a collection of which I need to retrieve distinct values. However when I'm using a query method to retrieve a Flux
of distinct values, it is not working. I defined the following query method, using a closed projection IdentifierOnly
:
@Repository
public interface FooBarRepository extends ReactiveCrudRepository<FooBar, String> {
Flux<IdentifierOnly> findDistinctByFooAndBar(String foo, String bar);
}
The document / collection class:
@Document
public class FooBar {
private String identifier; // not unique
private String foo;
private String bar;
// extra fields
// getters and setters
}
The closed projection:
public interface IdentifierOnly {
getIdentifier();
}
However the query that is executed and logged by the ReactiveMongoTemplate
is the following: find using query: { "foo" : "xxxx", "bar" : "yyyy" } fields: Document{{identifier=1}} for class: class org.example.models.FooBar in collection: fooBar
and is not returning any results in a distinct way, because it contains duplicates.
What am I doing wrong? How can I retrieve distinct values (identifiers) based on a specific query?
Upvotes: 0
Views: 955
Reputation: 18119
That does not work (yet). I filed DATAMONGO-1985 to investigate how we can integrate distinct queries.
MongoDB provides a distinct operation that requires exactly one field for retrieving distinct values. This operation is available on the Template API but not through the repository API. From a repository perspective, there's actually no possibility to specify the field which should be used for a distinct operation.
The code above forms an interesting case which uses all ingredients (distinct keyword, closed projection with a single field) that would be necessary to derive a distinct query.
Upvotes: 2