Saurabh Deshpande
Saurabh Deshpande

Reputation: 1221

Parse mongodb document into string variables

I am a MongoDB beginner. I am trying to use it with java api. I have few documents inserted into mongodb and I am done with connecting to mongo instance using java.

My challenge is, I am getting one document as a result of mongodb query through java.

The result is one document in mongo which looks like:

{ "_id" : { "$oid" : "528f13b5b55008f6487f7988"} , "NodeName" : "saurabhdeshpande" , "FirstName" : "saurabh" , "LastName" : "deshpande" }

I want to take all these returned values into string variables like

String nodename, String firstname, String lastname

Please suggest - Hw do i go about this?

Code I tried is -

    DBCursor cursor = coll.find();
        BasicDBObject query = new BasicDBObject("NodeName", name);

        cursor = coll.find(query);
        try {
            while (cursor.hasNext()) {

                System.out.println(cursor.next());
                DBObject tobj = cursor.next();
                details[0] = (String) tobj.get("NodeName");
                details[1] = (String) tobj.get("FirstName");
                details[2] = (String) tobj.get("LastName");

                System.out.println("in details ");
                for (int i = 0; i < details.length; i++) {
                    System.out.println("in details " + details[i]);
                }
            }
        } finally {
            cursor.close();
        }
        mongoClient.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

Upvotes: 0

Views: 4660

Answers (2)

4J41
4J41

Reputation: 5095

You are doing two cursor.next() in the same iteration which could cause runtime exception.

DBCursor cursor = coll.find();
    BasicDBObject query = new BasicDBObject("NodeName", name);

    cursor = coll.find(query);
    try {
        while (cursor.hasNext()) {

            //System.out.println(cursor.next());
            DBObject tobj = cursor.next();
            System.out.println(tobj);
            details[0] = (String) tobj.get("NodeName");
            details[1] = (String) tobj.get("FirstName");
            details[2] = (String) tobj.get("LastName");

            System.out.println("in details ");
            for (int i = 0; i < details.length; i++) {
                System.out.println("in details " + details[i]);
            }
        }
    } finally {
        cursor.close();
    }
    mongoClient.close();
} catch (UnknownHostException e) {
    e.printStackTrace();
}

Upvotes: 0

4J41
4J41

Reputation: 5095

Your result will be a BasicDBObject(which is basically a Map) say result.

String nodename = (String)result.get("NodeName");
String firstname = (String)result.get("FirstName");
String lastname= (String)result.get("LastName");

Upvotes: 2

Related Questions