我有一个包含员工证件的收藏夹。每个员工都有该员工当前参与的项目的一系列文档。问题是我不知道如何获取/查询项目的数组?
这是此类文档的示例。
{name : "employe name" , age : "..employe age" , phoneNr : 12334 , projects :
[{ projectName : "project name" , projectLeder : "project leader" }] }
这是一个示例代码,用于检索文档中除项目数组以外的值。
public void printEmployees() {
MongoCursor<Document> cursor = coll.find().iterator();
while(cursor.hasNext()) {
Document documentEmployee = cursor.next();
System.out.println((String) documentEmployee.get("name"));
System.out.println((Integer) documentEmployee.get("age"));
System.out.println((Integer) documentEmployee.get("phoneNr"));
//How do i query/extract the project array?
}
}
最佳答案
您可以尝试这样的事情。
while(cursor.hasNext()) {
Document documentEmployee = cursor.next();
System.out.println(documentEmployee.getString("name"));
System.out.println(documentEmployee.getInteger("age"));
System.out.println(documentEmployee.getInteger("phoneNr"));
//Extract
ArrayList projects = documentEmployee.get("project", ArrayList.class);
//Map
for (Object obj : projects) {
Document project = (Document) obj;
project.getString("projectName");
}
}