2017-03-01 74 views
2

我正在构建一个连接到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); 

是否有使用发现只得到了电影片名,然后显示方式只有价值?提前致谢。

编辑

在应该重复的问题,这个问题是关系到找到根据某个字段的一个特定的文档。这不是我需要的,我需要用一个字段填充组合框,但我需要获取所有文档。

+0

的[查找在MongoDB中收集一些值?]可能的复制(http://stackoverflow.com/questions/8327676/find-some-values-in-a-mongodb-collection) –

+0

我不t认为这是重复的,我不需要找到一个特定的文档,我需要列出他们都只是得到一个领域。 –

+0

什么是你的mongo db驱动程序版本? – Veeram

回答

2

如果你想在你的结果集只有特定的领域,你将需要使用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")); 
} 
1

而不是在想要返回的键中执行find()传递。在这种情况下,我相信你想要的只是标题。所以这应该工作:

DBCursor films = collection.find({},{"_id":0,"title":1});  
while(films.hasNext()){ 
    comboBox.addItem(films.next()); 
} 
1

DBObjectDBCollection是旧的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<>());