1

I am developing simple web application to learn jsp, mongodb, html. I have created an simple registration form in jsp which takes Name, Address and MobileNo information from user and insert it into mongodb, Now I want to retrieve this stored data and put value of every field in individual string variable.

Ex:

Name: varun;
Address: Nagpur;
MobileNo: 1234567890

Above data is stored in mongodb as:

{ 
"_id" : ObjectId("5259bacea6f8b1c4cd3431d3"), 
"Name" : "varun", 
"Address" : "nagpur", 
"MobileNumber" : "1234567890" 
}

Retrieved in jsp as follows:

MongoClient mongoC = new MongoClient(new ServerAddress("Localhost",27017));
DB database = mongoC.getDB("dbfrnzout");
DBCollection collec1 = database.getCollection("coll"); 
DBObject dock= collec1.findOne();
out.println(dock);

This code print one record as json document and I want to store value associated with every

field in individual string variable, something like this:

String s1 = varun ie. value of field Name

Need some guidance.

1
  • what is your question? Commented Oct 17, 2013 at 21:44

2 Answers 2

6

DBObject implements the Map<String, Object> interface so you should be able to do something like:

String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );

Be careful with the casts and make sure you are certain of the type and existence of each field. For numeric values I strongly recommend casting to a Number instead of Integer since MongoDB will re-cast values to a Long or Double at the weirdest times.

HTH, Rob.

Edit: If you are iterating over the results of a query you will have to inspect each document as it is returned from the iterator

DBCollection collec1 = database.getCollection("coll"); 
for( DBObject dock : collec1.find() ) {
    String name = (String) dock.get( "Name" );
    String address = (String) dock.get( "Address" );
    String mobileNumber = (String) dock.get( "MobileNumber" );

    // Do Something...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rob, Need further help. I am using "find()" method hence I have to use DBCursor instead of DBObject hence I cant use dock.get().. Is their any alternative..
0

Do something like this to get an object from a cursor

while (cursor.hasNext()) dbObject o = cursor.next()

Comments

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.