【问题标题】:Populating combobox with document fields使用文档字段填充组合框
【发布时间】:2017-03-01 18:18:07
【问题描述】:

我正在构建一个连接到 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 只获取电影标题,然后只显示值?提前致谢。

编辑

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

【问题讨论】:

  • 我不认为这是重复的,我不需要找到特定的文档,我需要将它们全部列出来获得一个字段。
  • 你的 mongo db 驱动版本是多少?
  • mongo-java-driver 3.4.2

标签: java mongodb


【解决方案1】:

如果您只想获取结果集中的特定字段,则需要使用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"));
}

【讨论】:

    【解决方案2】:

    而不是通过 find() 传递您想要返回的键。在这种情况下,我相信您想要的只是标题。所以这应该有效:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        • 1970-01-01
        • 2012-11-24
        • 2011-01-25
        相关资源
        最近更新 更多