简体   繁体   中英

How to use FindIterable to get the specific field from mongodb using java

Here,I'm trying to retrieve the status field if the name matches.How to use FindIterable instead of DBCursor.Can anyone please help me out ...

My code:

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

You simply load the cursor into a FindIterable object like so:

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

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

You simply load the cursor and fetch the document into the Document. for more info visit 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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM