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

Mongodb Java 3.4 - get fields from embedded document

我无法从我的嵌入式文档中检索地址字段。我还没有看到 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();
}   

这是文档结构。

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

我发现您的代码有两个问题:

  1. 这不会return一个文件

    Document temp_address_doc=temp_person_doc.get("address");  
    
  2. houseNo 属性是 Integer 而不是 String

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

如果您只是将 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);

注意要点:

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