如何使用FindIterable <document>从java

时间:2016-03-03 09:42:36

标签: java mongodb

在这里,如果名称匹配,我会尝试检索状态字段。如何使用FindIterable而不是DBCursor。任何人都可以帮助我...

我的代码:

  public String getStatus(String name) throws Exception{
             MongoClient mongo = new MongoClient("localhost",27017);
             MongoDatabase db = mongo.getDatabase("counter");
             MongoCollection<Document> col = db.getCollection("status");

            Document query = new Document();
            query.put("name", name);
            query.put("status", 1);

            Document fields = new Document();
            fields.put("status", 1);
            fields.put("_id", 0);

             DBCursor cursor = collection.find(query,fields);

             while(cursor.hasNext()){
                    System.out.println(cursor.next());
                }

        return "SUCCESS";
        }

2 个答案:

答案 0 :(得分:10)

您只需将光标加载到FindIterable对象中,如下所示:

FindIterable<Document> docs = col.find(query);
if (docs == null) {
    //no values found
}

for(Document doc : docs) {
    //access documents e.g. doc.get()
}

答案 1 :(得分:1)

您只需加载光标并将文档提取到Document中。有关更多信息,请访问https://dzone.com/articles/basic-java-crud-operations


DBCursor cursor = items.find(query);
while (cursor.hasNext()) {
    Document document = cursor.next();
    System.out.println(document.getString("identifier"));
}