Search code examples
javamongodbmongodb-querymongodb-java

Mongodb Java 3.4 - get fields from embedded document


I can't retrieve the address fields from my embedded document. I haven't seen any solutions for the 3.4 MongoDB driver.

System.out.println("Selecting Person ");

MongoCollection<Document> collection = mdb.getCollection("Person");
MongoCursor<Document> cursor = collection.find().iterator();

try {           
    while (cursor.hasNext()) {
        Document temp_person_doc=cursor.next();
        Document temp_address_doc=temp_person_doc.get("address");   
        String houseNo=temp_address_doc.getString("houseNo");       
    }
} finally {
    cursor.close();
}   

Here is the document structure.

{
    "_id" : "5aae9920982f271ba4b08735",
    "firstName" : "homer",
    "surname" : "simpson",
    "address" : {
        "houseNo" : 742,
        "address" : "evergreen terrace",
        "city" : "springfield",
    }
}

Solution

  • I can see two issues with your code:

    1. This will not return a document

      Document temp_address_doc=temp_person_doc.get("address");  
      
    2. The houseNo attribute is an Integer not a String

      String houseNo=temp_address_doc.getString("houseNo");  
      

    If you just change get("address") to get("address", Document.class) then you'll be on the right track.

    For example:

    Document temp_person_doc = cursor.next();
    
    // get the sub document _as a_ Document
    Document temp_address_doc = temp_person_doc.get("address", Document.class);
    
    // get the houseNo attribute (which is an integer) from the sub document
    Integer houseNo = temp_address_doc.getInteger("houseNo");
    // get the address attribute (which is a string) from the sub document
    String address = temp_address_doc.getString("address");
    
    // prints 742
    System.out.println(houseNo);    
    // prints evergreen terrace
    System.out.println(address);
    

    Key points to note:

    • You must read the sub document as a Document
    • You must read the houseNo attribute as an Integer