【问题标题】:Map document to object将文档映射到对象
【发布时间】:2017-02-03 18:59:37
【问题描述】:
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() 信息,我该怎么做?光标只返回一个字符串...

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 个相同项目的列表...

【问题讨论】:

  • 正在寻找 JsonObjectMapper..你是吗?

标签: java mongodb mongodb-query


【解决方案1】:

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

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

【讨论】:

  • 一些结果给我这个错误:java.util.NoSuchElementException
  • 您能否从您的收藏中添加一个文档并更新代码?您尝试映射的字段不在结果集中是导致异常的原因。
  • 移动 basicBOE b = new basicBOE();在循环内。
  • Np。请在此处阅读有关如何在 java 中命名的信息。 www.oracle.com/technetwork/java/codeconventions-135099.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2023-04-02
  • 2019-05-27
  • 2015-12-02
  • 1970-01-01
  • 2021-04-13
  • 2012-04-23
相关资源
最近更新 更多