CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > How to > MongoDB Document to POJO Class in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

MongoDB Document to POJO Class in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 ยท 3 min read ยท 0 Comments
Share: in X
check MongoDb database size

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.

Related Posts:

  • Update MongoDB Document
  • Delete in MongoDB
  • MySQL Commands for Developers
  • Pagination and Sorting in Spring Boot
  • MongoDB $expr Expressive Query Operator
  • Sort List of Objects in Java
Tags:javamongodb
Was this article helpful?
โ† Previous ArticleMongoCollection in Spring Boot
Next Article โ†’What is MongoDB?

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
ยฉ 2026 CoderSathi. All rights reserved. Privacy Policy ยท Sitemap