在mongodb中找到与集合不同的对象 [英] Finding distinct from collections in mongodb
本文介绍了在mongodb中找到与集合不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们先前用于从集合中查找不同元素的实现曾经是:
Our previous implementation for finding distinct elements from a collection used to be :
List<String> names = mongoClient.getDB(dbName).getCollection(collectionName).distinct(NAME_KEY);
尝试将其升级到使用mongo 3.3.0+的当前实现是:
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>
也尝试过
.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
.
推荐答案
您可以尝试类似的方法.
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());
}
这篇关于在mongodb中找到与集合不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文