Finding distinct from collections in mongodb

社会主义新天地 提交于 2019-12-20 02:35:19

问题


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.


回答1:


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());
 }


来源:https://stackoverflow.com/questions/40246302/finding-distinct-from-collections-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!