Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding distinct from collections in 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);

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.

like image 699
Naman Avatar asked Oct 25 '16 17:10

Naman


People also ask

Can we use distinct with find in MongoDB?

Both the find and distinct operations are very useful when it comes to retrieving data from MongoDB. The find operation returns the data all at once or according to the query and projection. The distinct operation has a special functionality of retrieving unique values of a specified field.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I run a distinct query in MongoDB compass?

You can do this via aggregation framework in Compass, using $unwind and $group. The $unwind is performed to create a unique document for each element in the target array, which enables the $addToSet operator in the $group stage to then capture the genres as distinct elements.


1 Answers

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());
 }
like image 161
s7vr Avatar answered Oct 14 '22 13:10

s7vr