0

I am new to MongoDB and trying to get a collection's result into java class object. While collection.find() returns a cursor to Document class and most of the operations are done on this class only, I tried putting a codecRegistry to my POJO. I can get some functions working but I dont have the flexibility as most of the methods work on Document class and I am unable to cast to my class.

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());

}

In this code, I am able to iterate over the cursor and I am getting the output as

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

What I want to achieve is getting these output in an object of the class bookingMaster and use it the way I want. Is there a way to do that??

Piyush Kumar
  • 157
  • 1
  • 2
  • 14
  • Use the [Java POJO and CodecRegistry](https://mongodb.github.io/mongo-java-driver/3.12/driver/getting-started/quick-start-pojo/) for mapping between the Java object and the MongoDB document - try using the _default codec registry_. – prasad_ Apr 13 '20 at 13:37
  • The api page is not very clear about the implementation of the same.I want to understand the way how I can exactly map my data into POJO. – Piyush Kumar Apr 13 '20 at 17:15
  • _"I want to understand the way how I can exactly map my data into POJO"_: Where is the data you want to map? First, you have to create a POJO Java class for the `bookingMaster` (you had mentioned in the code). Please post that code for the same. Also, see this post about [What is a JavaBean?](https://stackoverflow.com/questions/11406977/what-is-a-java-bean) – prasad_ Apr 14 '20 at 04:31

0 Answers0