Reputation: 83
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?
Upvotes: 1
Views: 2312
Reputation: 1878
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");
}
Upvotes: 1