简体   繁体   中英

Extract Multiple Fields Using MongoDB 3.2.0 Java Driver

Using the MongoDB 3.2.0 Java driver, which offers a Document object that seems different from a "BasicDBObject" or "DBObject", I would like to extract all the fields in a given document. For example, I have this document:

{ "sponsor" : "ABC Bicycles", "start" : "Herndon", "miles" : 50 }

I'd like to extract the values of "sponsor", "start", and "miles" using an Iterator. I've tried:

theSponsor = cursor.next().get("sponsor").toString();

which works fine for the "sponsor" field, but how can I pull the values of "start" and "miles" for this same question, using the same cursor? Perhaps I need something other than

MongoCursor<Document> cursor = collection.find().iterator();

You can try the following:

String sponsor;
String start;
String miles;
Document doc;

while(cursor.hasNext()){
    doc = cursor.next();
    sponsor = doc.get("sponsor").toString();
    start = doc.get("start").toString();
    miles = doc.get("miles").toString();

    // Process your values and go to the next record 
}

You should check if your fields exist in the Document (as far as I remember, Mongo API used to throw some Exception in case it couldn't find the field). And of course, before calling toString() method, check if the objects aren't null to avoid NullPointerException . :)

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