Mongodb Java 3.4 - 从嵌入式文档中获取字段

Pot*_*Man 1 java mongodb mongodb-java mongodb-query

我无法从嵌入的文档中检索地址字段。我还没有看到 3.4 MongoDB 驱动程序的任何解决方案。

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();
}   
Run Code Online (Sandbox Code Playgroud)

这是文档结构。

{
    "_id" : "5aae9920982f271ba4b08735",
    "firstName" : "homer",
    "surname" : "simpson",
    "address" : {
        "houseNo" : 742,
        "address" : "evergreen terrace",
        "city" : "springfield",
    }
}
Run Code Online (Sandbox Code Playgroud)

gly*_*ing 5

我可以看到您的代码有两个问题:

  1. 这不会返回文档

    Document temp_address_doc=temp_person_doc.get("address");  
    
    Run Code Online (Sandbox Code Playgroud)
  2. houseNo属性Integer不是一个String

    String houseNo=temp_address_doc.getString("houseNo");  
    
    Run Code Online (Sandbox Code Playgroud)

如果您只是更改get("address")为,get("address", Document.class)那么您将走在正确的轨道上。

例如:

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);
Run Code Online (Sandbox Code Playgroud)

需要注意的要点:

  • 您必须阅读子文档作为 Document
  • 您必须将该houseNo属性作为Integer