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

标签 java mongodb mongodb-query mongodb-java

我无法从嵌入文档中检索地址字段。我还没有看到任何针对 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. 这不会返回文档

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

注意要点:

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

关于java - Mongodb Java 3.4 - 从嵌入文档中获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49351629/

相关文章:

java - 如何获取JUnit中src/test/resources目录的路径?

java - RxJava : How to convert List of objects to List of another objects

mongodb在不知道对象节点的情况下删除嵌套对象

java - hive 脚本问题

java - 将 wsit-client.xml 中的位置导入到另一个 jar 中的文件,使用 URL 字符串在类路径上定位文件

javascript - 如何在现有 Node 之间创建/匹配多个关系? (通过相同的参数)

mongodb - 如何查询不是 ObjectId 类型的 _id

node.js - findOneAndUpdate 在插入时返回 null?

java - 如何通过java将json数据推送到MONGODB中的数组对象中

通过 zip 进行 MongoDB 地理空间搜索