---
title: "What are the ways of converting a Java object to a MongoDB document and vice versa?"  
description: "What are the ways of converting a Java object to a MongoDB document and vice versa?"  
author: "simron shukla"  
published: 2018-03-11  
canonical: https://answers.mindstick.com/qa/39738/what-are-the-ways-of-converting-a-java-object-to-a-mongodb-document-and-vice-versa  
category: "programming"  
tags: ["java programming"]  
reading_time: 1 minute  

---

# What are the ways of converting a Java object to a MongoDB document and vice versa?

What are the ways of converting a [Java](https://www.mindstick.com/articles/12086/arrays-in-java-non-rectangular-arrays-part-5) object to a [MongoDB](https://www.mindstick.com/articles/337565/understanding-document-stores-a-look-at-mongodb-vs-couchdb) [document](https://answers.mindstick.com/qa/49880/how-to-open-a-pub-document-on-mac-os-x) and vice versa?

\

## Answers

### Answer by Arti Mishra

**"Converting Java Object to MongoDB document"** Generally, MongoDB document uses **JSON** for converting your **Java Object (POJO)** to **JSON document** and use it in **MongoDB.** You can use **Gson library** to convert your Java Object(POJO) to JSON\
Converting **POJO(Plain Old Java Object)** to MongoDB Document

- **Firstly, Create Gson object**

Gson gson=new Gson();

- **Convert Your Java Object to JSON**

String json = gson.toJson(POJO);

- **Add the following code in your project.**

FileWriter writerObj = new FileWriter("file.json"); writerObj.write(json); writerObj.close();\
**Converting MongoDB Document back to Java Object(POJO) :**

- **Firstly, Create Gson object**

Gson gson=new Gson();\

- **Convert it back to Java Object (POJO)**

BufferedReader br = new BufferedReader(new FileReader("file.json")); Data POJO = gson.fromJson(br,POJO.class); System.out.println(POJO); \


---

Original Source: https://answers.mindstick.com/qa/39738/what-are-the-ways-of-converting-a-java-object-to-a-mongodb-document-and-vice-versa

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
