Search code examples
javamongodbmongodb-java

MongoDB Reading from Nested Documents


I have a document with nested documents within, I thought as per a filter I would be able to specify something like data.sms.mobileNumber. However that doesn't work.

How would I read the data in the data.sms.mobileNumber field, using the the standard Document getString request?

Example Document:

{ "_id" : ObjectId("59b850bd81bacd0013d15085"), "data" : { "sms" : { "message" : "Your SMS Code is ABCDEFG", "mobileNumber" : "+447833477560" } }, "id" : "b0a3886d69fc7319dbb4f4cc21a6039b422810cd875956bfd681095aa65f6245" }

Example Field get String request:

document.getString("data.sms.message")

Solution

  • The 'path' data.sms.message refers to a structure like this:

    +- data
      |
      +- sms
        |
        +- message
    

    To read this using the Java driver you have to read the data document, then the sms sub document then the message attribute of that sub document.

    For example:

    Document data = collection.find(filter).first();
    Document sms = (Document) data.get("sms");
    String message = sms.getString("message");
    

    Or, the same thing with shortcuts:

    String message = collection.find(filter).first()
        .get("sms", Document.class)
        .getString("message");
    

    Update 1 in answer to this question: "I have a case where I have an array of documents in a document, how would I go about getting a field from a document in the array?" Let's assume you have a document with an array field named details and each detail has name and age. Something like this:

    {"employee_id": "1", "details": [{"name":"A","age":"18"}]}
    {"employee_id": "2", "details": [{"name":"B","age":"21"}]}
    

    You could read the array element like so:

        Document firstElementInArray = collection.find(filter).first()
            // read the details as an Array 
            .get("details", ArrayList.class)
            // focus on the first element in the details array
            .get(0);
    
        String name = firstElementInArray.getString("name");