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: db.locations.distinct("categories");
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 =
db.getCollection("locations").distinct("categories").iterator();
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.
I'll create an example database in the MongoDB shell and go as far as delivering a distinct query in Java with the 3.0 driver.
In the shell, create a database with demo data:
use imagedb;
db.createCollection("image_files");
db.image_files.insert({ file: "1.jpg", aspect: "4:3" });
db.image_files.insert({ file: "1.jpg", aspect: "16:9" });
db.image_files.insert({ file: "2.jpg", aspect: "4:3" });
db.image_files.insert({ file: "2.jpg", aspect: "16:9" });
db.image_files.insert({ file: "3.jpg", aspect: "2.35:1" });
In the shell, we may find distinct records.
> db.image_files.distinct('file');
[ "1.jpg", "2.jpg", "3.jpg" ]
How to do it with Java and the MongoDB 3.0 driver?
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class Main {
public static void main(String[] args) {
MongoClient mongo = new MongoClient();
MongoDatabase db = mongo.getDatabase("imagedb");
MongoCollection<Document> filesCollection = db.getCollection("image_files");
MongoCursor<String> files = filesCollection.distinct("file", String.class).iterator();
while(files.hasNext()) {
System.out.println(files.next());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With