2015-07-10 146 views
3

您好,我正在使用mongodb java驅動程序3.0。我有這樣一個文件:Mongodb java驅動程序3.0查詢

db.employee.find().pretty() 

    "_id" : ObjectId("559e4ae4aed7561c94e565d5"), 
    "empid" : 1, 
    "name" : "abc", 
    "dob" : "17/05/1990", 
    "address" : [ 
      "559e4ae3aed7561c94e565d3", 
      "559e4ae4aed7561c94e565d4" 
    ] 

我想在地址字段查詢並獲取所有的地址(在我的情況下,上述這些值)沒有指定其值。我的代碼是:

FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
     new Document("address", 559e4ae3aed7561c94e565d3)); 
iterable.forEach(new Block<Document>() { 
    @Override 
    public void apply(final Document document) 
     System.out.println(document); 
    } 
}); 

我不想手動指定地址。如果我查詢地址,我應該得到這兩個值。有什麼建議麼?

+0

爲什麼你不能得到整個文件?這是默認情況下發生的情況,除非您在投影中特別要求「只匹配字段」之類的內容。 –

回答

6

得到了答案,我們可以查詢其他已知字段爲例如:empid而不是返回整個文檔,只返回您需要的字段(在我的情況下是地址)。

FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
      new Document("empid", 1)); 
    iterable.forEach(new Block<Document>() { 
     @Override 
     public void apply(final Document document) { 
      System.out.println(document.get("address").toString()); 
     } 
    });