discodowney
discodowney

Reputation: 1507

Using distinct in a mongo query in java

I'm trying to use a distinct query for mongodb in java. looking at this link it says I can just pass in the field name:

https://api.mongodb.org/java/3.0/com/mongodb/DBCollection.html#distinct-java.lang.String-

So I have:

searchResults = playerCollection.distinct("team");

But it says it cannot resolve method distinct(java.lang.String)

It seems to think i have to put in another class parameter. But I do not want any subset of the results. I just want all the distinct teams.

Update: How I instantiated the collection:

uri = new MongoClientURI("mongodb://<MongoURI>");
mongoClient = new MongoClient(uri);
mongoDB = mongoClient.getDatabase(uri.getDatabase());
playerCollection =  mongoDB.getCollection("players");

Upvotes: 0

Views: 11248

Answers (2)

Saleem
Saleem

Reputation: 8978

Please check which driver version you have? I believe Distinct(<string>) was in pre 3.0. and now it's gone for good.

Please check

http://api.mongodb.org/java/3.0/com/mongodb/async/client/MongoCollection.html#distinct-java.lang.String-java.lang.Class-

Also check type of mongoDb.getCollection, it should be MongoCollection<Document> not `DbCollection'

Example:

DistinctIterable<Double> documents = playerCollection.distinct("aID", Double.class );

for (Double document : documents) {
    System.out.println(document);
}

Where aID is your distinct field. Second parameter of distinct represents type of aIDproperty in MongoDB document.

Hopefully, it will help you.

Upvotes: 1

AxxE
AxxE

Reputation: 833

The method you are trying to use is defined for the DBCollection class but you are calling it for a MongoCollection<Document> class object. Hence the error, because both classes have mathods with the same name but different signatures. The way to use the method you want is by changing the way you instantiate the DB and collection objects.

uri = new MongoClientURI("mongodb://<MongoURI>");
mongoClient = new MongoClient(uri);

//http://api.mongodb.org/java/3.0/com/mongodb/DB.html
// create a object of the DB class
mongoDB = mongoClient.getDB(uri.getDatabase());

//http://api.mongodb.org/java/3.0/com/mongodb/DB.html#getCollection-java.lang.String-
playerCollection =  mongoDB.getCollection("players");

// now that you have a DBCollection object you can use the distinct(String) method
searchResults = playerCollection.distinct("team");

Also, the deprecation list for v3.0 (http://api.mongodb.org/java/3.0/deprecated-list.html#class) does not include the DB nor the DBCollection class, so you should be fine.

Upvotes: 1

Related Questions