2017-03-01 76 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<>());