将文档映射到对象

时间:2017-02-03 18:59:37

标签: java mongodb mongodb-query

public void SearchForDate(String date) {
Information object = new Information();
List<Information> list = new ArrayList<Information>();
MongoCursor<Document> cursor = collection.find(eq("date", date)).iterator();
while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
}

嗨,我想在信息类的新对象上插入cursor.next()。toJson()信息,我该怎么做?光标只返回一个String ...

public void BuscarPorPalabra(String date) {
    MongoCursor<Document> cursor = collection.find(eq("date", date)).iterator();
    basicBOE b = new basicBOE();
    while (cursor.hasNext()) {
       Document element = cursor.next();
       b.setDepartament(element.getString("departament"));
       b.setText(element.getString("text"));
       b.setTitle(element.getString("title"));
       list.add(b);
    }
}

我知道了,但我现在遇到了一个新问题,最后一项覆盖了列表中的另一个对象,并且列出了64个相同的项目......

1 个答案:

答案 0 :(得分:0)

您只需要迭代结果集并将Document映射到您的对象。

while (cursor.hasNext()) {
     Document document = cursor.next();
     Information object = new Information();
     object.setSomeField(document.getString("somefield"));
}