MongoDB Document to POJO Class in Java

In this post, we will learn to map MongoDB Document to POJO Class in Java directly from org.bson.Document object to Java POJO or Java Bean. By default, MongoDB Java Driver maps MongoDB collection document to org.bson.Document object.

1. Employee document sample

{
  "_id": "507f191e810c19729de860ea",
  "name": "Coder Sathi",
  "department": "Engineering",
  "salary": 50000
}

2. Insert employee document with BSON document

We can use org.bson.Document object to insert into database and also fetch data from the database. Let’s see an example below where we will insert data into the database first and later fetch the data to make sure the data is inserted successfully.

@Test
void shouldInsertDataWithDefaultImplementation() {

        // Creating mongo client instance with default 
	MongoClient mongoClient = MongoClients.create();

        // Creating the instance of Mongo Collection 
	MongoCollection<Document> employeesCollection =mongoClient.getDatabase("myDatabase")
			.getCollection("employees");

        // Creating employee object and setting the value
	Document employee = new Document("name", "Coder Sathi");
		employee.append("department", "Engineering");
		employee.append("salary", 50000);

	employeesCollection.insertOne(employee);

	// Fetching recently inserted employee data

	Bson findByName = new Document("name", "Coder Sathi");

	Document coderSathi = employeesCollection.find(findByName).first();

	assertNotNull(coderSathi);
	assertEquals("Coder Sathi", coderSathi.get("name"));

}

3. Insert employee document using POJO

The main scope of this post is to map POJO with the MongoDB document. First, we need to create a POJO class. So let’s create an Employee POJO:

3.1 Create employee POJO class

public class Employee{
        private String name;
	private String department;
	private double salary;
	
	//Getters and Setters
}

3.2 Set employee data into employee pojo

Employee employeePojo = new Employee();
employeePojo.setDepartment("Account");
employeePojo.setName("Virat Kohli");
employeePojo.setSalary(60000);

employeesCollection.insertOne(employeePojo); // Error

When we try to use employeePojo object to insert, it doesnot allow us. Hence, we need to create MongoCollection instance with codec registry.

Let’s see the full example:

@Test
void shouldInsertWithPojoImplementation() {

    // Creating mongo client instance with default 
    MongoClient mongoClient = MongoClients.create();


    // Creating employee object and setting the value
    Employee employeePojo = new Employee();
    employeePojo.setDepartment("Account");
    employeePojo.setName("Virat Kohli");
    employeePojo.setSalary(60000);

    // Creating a default codec registery
    CodecRegistry pojoCodecRegistry = CodecRegistries.fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    // Creating ins instance of MongoCollection for employee with codec registry
    MongoCollection<Employee> employeePojoCollection = mongoClient.getDatabase("myDatabase").getCollection("employees", Employee.class).withCodecRegistry(pojoCodecRegistry);

    // Inserting data into database directly from Employee object
    employeePojoCollection.insertOne(employeePojo);


    // Creating filter to make sure the employee with name Virat Kohli is inserted successfully or not.
    Bson findByName = new Document("name", "Virat Kohli");

    Employee viratKohli = employeePojoCollection.find(findByName).first();

    assertNotNull(viratKohli);
    assertEquals(employeePojo.getName(), viratKohli.getName());
}

The test is passed successfully. It means we are able to map POJO with mongodb document directly with the help of the codec registry.

4. Conclusion

In this post, we learned to map from org.bson.Document object to POJO for MongoDB document to Java class respectively.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments