6

Our previous implementation for finding distinct elements from a collection used to be :

List<String> names = mongoClient.getDB(dbName).getCollection(collectionName).distinct(NAME_KEY);

Trying to upgrade this into the current implementation with mongo 3.3.0+ as tried is :

List<String> names = mongoClient.getDatabase(dbName)
                        .getCollection(collectionName, TDocType.class)
                        .distinct(NAME_KEY, String.class); // compile error - required Class<TResult> 

Have also given a try to

.distinct(NAME_KEY, TDocType.class)  // doesn't work                      

What shall be the target type of the iterable in this case?

Edit - The question is not a duplicate of Get distinct records values since the implementation has changed over the upgrade of mongodb-java-driver.

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353

2 Answers2

8

Improved answer from @jyemin

List<String> list = mongoClient.getDatabase(dbName)
                .getCollection(collectionName, TDocType.class)
                .distinct(NAME_KEY, String.class)
                .into(new ArrayList<>()); 

Original answer

You can try something like this.

DistinctIterable<String> iterable = mongoClient.getDatabase(dbName).
            .getCollection(collectionName, TDocType.class).distinct(NAME_KEY, String.class);
MongoCursor<String> cursor = iterable.iterator();
List<String> list = new ArrayList<>();
while (cursor.hasNext()) {
    list.add(cursor.next());
 }
takanuva15
  • 1,286
  • 1
  • 15
  • 27
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • Thanks. Also this can be further improved as `for(String str : iterable) { list.add(str); }` instead of using Cursor above. The way I am using it is `List list = Lists.newArrayList(mongoClient.getDatabase(dbName).getCollection(collectionName, TDocType.class).distinct(NAME_KEY, String.class));` where the `Lists` is from google collection. – Naman Oct 27 '16 at 17:43
  • 7
    Or more simply: List list = mongoClient.getDatabase(dbName).getCollection(collectionName, TDocType.class).distinct(NAME_KEY, String.class).into(new ArrayList<>()); – jyemin Nov 11 '16 at 20:18
0

for those who already have org.codehaus.groovy:groovy in their deps :

// import static org.codehaus.groovy.runtime.DefaultGroovyMethods.toSet;.
toSet(distinctIterable);

Example

DistinctIterable<String> distinctIterable = getCollection()
            .distinct(FIELD_ID, query.getQueryObject(), String.class);
return toSet(distinctIterable);
boly38
  • 1,806
  • 24
  • 29