Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 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();
like image 948
ThisClark Avatar asked May 03 '15 03:05

ThisClark


2 Answers

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.

like image 72
jyemin Avatar answered Nov 10 '22 11:11

jyemin


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());
    }
  }
}
like image 4
ThisClark Avatar answered Nov 10 '22 11:11

ThisClark