MongoDB 3.0 developer Java query is different without filter
How can I execute a query with the MongoDB 3.0 Java driver?
I am trying to query unique category records from a location collection in MongoDB. In Mongo shell it is very simple:db.locations.distinct("categories");
In Java, this is 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();
source to share
To avoid great casts, the MongoCollection API allows you to provide the expected individual value type for a field. For example, if you know that all lines are, 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 cannot guarantee anything about the value types for the field you are requesting.
source to share
I'll create a sample database in the MongoDB wrapper and get to delivering a separate Java query with Driver 3.0.
In the shell, create a database with sample 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 can find different entries.
> db.image_files.distinct('file');
[ "1.jpg", "2.jpg", "3.jpg" ]
How do I do this with Java and 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());
}
}
}
source to share