2016-03-03 1271 views
1

在这里,如果名称匹配,我试图检索状态字段。如何使用FindIterable而不是DBCursor.Can任何人都请帮助我...如何使用FindIterable <Document>使用java从mongodb获取特定字段

我的代码:

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"; 
     } 

回答

7

您只需将光标加载到FindIterable对象,像这样:

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

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

非常感谢Hughzi – dev777

+0

@ dev777您欢迎,乐意帮忙! – Hughzi

相关问题