Java 用文档字段填充组合框
我正在构建一个连接到MongoDB的关于电影的Java应用程序,我想创建一个组合框,以便用电影名称填充它。我的问题是我发现的唯一方法是用完整的文档填充它,而不是仅仅获取电影名称 这就是我到目前为止所做的:Java 用文档字段填充组合框,java,mongodb,Java,Mongodb,我正在构建一个连接到MongoDB的关于电影的Java应用程序,我想创建一个组合框,以便用电影名称填充它。我的问题是我发现的唯一方法是用完整的文档填充它,而不是仅仅获取电影名称 这就是我到目前为止所做的: DBCursor films = collection.find(); while(films.hasNext()){ comboBox.addItem(films.next()); } 以下是我创建文档的方式: DBCollection table = db.getCol
DBCursor films = collection.find();
while(films.hasNext()){
comboBox.addItem(films.next());
}
以下是我创建文档的方式:
DBCollection table = db.getCollection("films");
BasicDBObject document = new BasicDBObject();
document.put("title", titulo.getText());
document.put("arg", argumento.getText());
document.put("date", fecha.getText());
document.put("genres", genres);
table.insert(document);
有没有一种方法可以使用find只获取电影标题,然后只显示值?提前谢谢
编辑
在假定的重复问题中,该问题与基于某个字段查找特定文档有关。这不是我需要的,我需要用一个字段填充一个组合框,但我需要获取我的所有文档。而不是对要返回的键进行查找。在这种情况下,我相信你想要的只是头衔。因此,这应该是可行的:
DBCursor films = collection.find({},{"_id":0,"title":1});
while(films.hasNext()){
comboBox.addItem(films.next());
}
如果希望仅获取结果集中的特定字段,则需要使用并指定要在“投影”参数中获取的字段,如下所示:
// Retrieve only the title of all the documents that can be found in the collection
DBCursor cursor = collection.find(
new BasicDBObject(), new BasicDBObject("title", Boolean.TRUE)
);
while (cursor.hasNext()) {
// Add the value of the title to the combo box
comboBox.addItem((String) cursor.next().get("title"));
}
DBObject和DBCollection是旧的2.x类
您可以尝试类似于3.x驱动程序的功能
import static com.mongodb.client.model.Projections.*;
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> col = db.getCollection("films");
List<String> titles = col.find().projection(fields(include("titles"), excludeId())).map(document -> document.getString("titles")).into(new ArrayList<>());
可能的重复我不认为这是重复的,我不需要找到一个特定的文档,我需要列出它们,只需要一个字段。您的mongo db驱动程序版本是什么?mongo java驱动程序3.4.2