Java MongoDB 3.0 driver query distinct without filter

匆匆过客 提交于 2019-12-19 08:54:06

问题


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();

回答1:


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.




回答2:


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());
    }
  }
}


来源:https://stackoverflow.com/questions/30009847/java-mongodb-3-0-driver-query-distinct-without-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!