1

How can I access value from key/value pair from the subdocument (Mongodb) using Java?

{ "_id" : { "key1" : "val1"} , "key2" : “val2” , "subdoc" : { "key3" : "val3" , "key4" : "val4" }

    DB db = (new MongoClient("localhost", 27017)).getDB("nov2014");         
    DBCollection dbCollection = db.getCollection("student");    

    BasicDBObject basicDBObj = new BasicDBObject();
    basicDBObj.put("key1", " val1");            

    DBCursor dbCursor = dbCollection.find(basicDBObj);          
    while(dbCursor.hasNext()){
        BasicDBObject dbObject = (BasicDBObject)dbCursor.next();    
        System.out.println(“Key 2: ” = dbObject.getString("key2");
        System.out.println(“Key 3: ” = dbObject.getString("subdoc.key3");
        System.out.println(“Key 4: ” = dbObject.getString("subdoc.key4");                           
    }

In the output values of key3 and key 4 are null. Can someone tell me how to access values from the subdocument?

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Vinita
  • 83
  • 1
  • 1
  • 5
  • Please see the answer for http://stackoverflow.com/questions/12166573/java-mongodb-getting-value-for-sub-document – Abhi Dec 17 '14 at 15:01

1 Answers1

1

Use the following code snippet please:

DB db = (new MongoClient("localhost", 27017)).getDB("nov2014");         
DBCollection dbCollection = db.getCollection("student");    

BasicDBObject basicDBObj = new BasicDBObject();
basicDBObj.put("key1", " val1");            

DBCursor dbCursor = dbCollection.find(basicDBObj);          
while(dbCursor.hasNext()){
    BasicDBObject dbObject = (BasicDBObject)dbCursor.next();    
    System.out.println(“Key 2: ” = dbObject.getString("key2");
    System.out.println(“Key 3: ” = ((BasicDBObject)dbObject.get("subdoc")).get("key3");
    System.out.println(“Key 4: ” = ((BasicDBObject)dbObject.get("subdoc")).get("key4");                         
}
evandrix
  • 6,041
  • 4
  • 27
  • 38
sitakant
  • 1,766
  • 2
  • 18
  • 38
  • It is straight forward and works well. Btw, I have solved using - http://stackoverflow.com/questions/5015844/parsing-json-object-in-java. Thanks again. – Vinita Dec 19 '14 at 11:32