从嵌套的mongodb文档中访问值

时间:2014-12-17 14:48:00

标签: mongodb

如何使用Java从子文档(Mongodb)访问键/值对的值?

{ "_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");                           
    }

key3和key 4的输出值为null。有人能告诉我如何从子文档中访问值吗?

1 个答案:

答案 0 :(得分:1)

请使用以下代码段:

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");                         
}