ThisClark ThisClark - 1 year ago 80
Java Question

Java MongoDB 3.0 driver query distinct without filter

How may I query distinct with the Java MongoDB 3.0 driver?

I am attempting to query unique categories records from a locations collection in MongoDB. In the Mongo shell, this is very simple:


In Java, it's not the same.

MongoClient client = new MongoClient();
MongoDatabase db = client.getDatabase("yelp");

//this will not compile, although examples from before 3.0 do it this way
MongoCursor<Document> c =

Answer Source

To let you avoid casts for distinct, the MongoCollection API lets you provide the expected type of the distinct values for the field. So if you know they are all strings, for example, you can write:

MongoCursor<String> c = 
   db.getCollection("locations").distinct("categories", String.class).iterator();

or all numbers:

MongoCursor<Number> c = 
   db.getCollection("locations").distinct("categories", Number.class).iterator();

You can still do:

MongoCursor<Object> c = 
   db.getCollection("locations").distinct("categories", Object.class).iterator();

if you can't guarantee anything about the types of the values for the field you're querying.