我正在构建一个连接到 MongoDB 的有关电影的 Java 应用程序,并且我想创建一个 ComboBox,以便可以用电影名称填充它。我的问题是我发现的唯一方法是用完整的文档填充它,而不是仅仅获取电影名称。
这是我到目前为止所拥有的:
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 只获取电影标题,然后只显示值?提前致谢。
编辑
在假定的重复问题中,该问题与根据其中一个字段查找特定文档有关。这不是我需要的,我需要用一个字段填充组合框,但我需要获取所有文档。
最佳答案
如果您只想获取结果集中的特定字段,则需要使用 find(DBObject query, DBObject projection)
并指定要在投影参数中获取的字段,如下所示:
// 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"));
}
关于java - 使用文档字段填充组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539109/