0

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();
1
  • How about storing the object? while (cursor.hasNext()) { Document doc = cursor.next(); theSponsor = doc.get("sponsor").toString(); theStart = doc.get("start").toString(); theMiles = doc.get("miles").toString();} ? Commented Jan 9, 2016 at 17:02

1 Answer 1

1

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. :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! This works great! I really appreciate your help with this. I will try to figure out how to "accept" this answer.
I'm happy my advice was useful. It's just a common practice working with iterators / cursors ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.