2

I'm building a Java application connected to MongoDB about films, and I want to create a ComboBox so I can populate it with the film names. My problem is the only way I have found is populating it with the full document, instead of just getting the film name.

This is what I have so far:

DBCursor films = collection.find();     
while(films.hasNext()){
    comboBox.addItem(films.next());
}

This is how I create the document:

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

Is there a way to use find to only get the film titles and then display only the value? Thanks in advance.

EDIT

In the supposed duplicated question, the question is related to finding a specific document based on one of its fields. That's not what I need, I need to populate a combobox with one field, but I need to get all my documents.

qapt
  • 101
  • 2
  • 12

3 Answers3

2

If you want to get only specific fields in your result set, you will need to use find(DBObject query, DBObject projection) and specify the fields to get in the projection parameter as 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"));
}
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
1

Rather than do a find() pass in the keys you want returned. In this case I believe all you want back is the title. So this should work:

DBCursor films = collection.find({},{"_id":0,"title":1});     
while(films.hasNext()){
    comboBox.addItem(films.next());
}
Woodsy
  • 3,177
  • 2
  • 26
  • 50
1

DBObject and DBCollection are old 2.x classes.

You can try something like with 3.x driver.

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<>());
s7vr
  • 73,656
  • 11
  • 106
  • 127