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

时间:2018-03-18 18:48:12

标签: java mongodb mongodb-query mongodb-java

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

for(var i = 0; i < enemies.length; i++) {
    enemies[i].Draw(i);
    enemies[i].Move();
}

this.Draw = function(i) {

    ctx.fillStyle = 'orange';
    ctx.fillRect(this.X, this.Y, 30, 30);
    ctx.fillStyle = 'white';
    ctx.fillText(i, this.X, this.Y);//i would be the index in the array and changes with splice()
}

这是文档结构。

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

1 个答案:

答案 0 :(得分:2)

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

  1. 这不会返回文档

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

    String houseNo=temp_address_doc.getString("houseNo");  
    
  3. 如果您只是将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