首页 > 解决方案 > 如何将 mongoDB 的输出转换为 java 对象(使用对象工厂)

问题描述

我是 MongoDB 的新手,并试图将集合的结果放入 java 类对象中。虽然 collection.find() 将光标返回到 Document 类并且大多数操作仅在此类上完成,但我尝试将 codecRegistry 放入我的 POJO。我可以让一些功能正常工作,但我没有灵活性,因为大多数方法都适用于 Document 类,我无法转换为我的类。

FindIterable<Document> iterable = database.getCollection("bookingTest").find()
            .sort(Sorts.ascending("bookingId"));
    MongoCursor<Document> cursor1 = iterable.iterator();

    List<Document> list1 = new ArrayList<Document>();
try {
        while (cursor1.hasNext()) {

            list1.add(cursor1.next());

        }
    }

    finally {
        cursor1.close();
    }

    for (Document document : list1) {

        bookingMaster bm = new bookingMaster();
        System.out.println("id is " + document.toJson().toString());

}

在这段代码中,我能够遍历光标,我得到的输出为

id is {"_id": {"$oid": "5e93034001c18267dde36f5c"}, "bookingDay": "Tuesday", "bookingEndTime": "12:00", "bookingId": 1, "bookingPerson": "piyush.411031@gmail.com", "bookingStartTime": "10:00", "bookingTeam": "ADM"}

我想要实现的是在类的对象中获取这些输出bookingMaster并以我想要的方式使用它。有没有办法做到这一点??

标签: javamongodb

解决方案


推荐阅读