Insert Document In MongoDB

Mongodb stores documents in bson form. Just like we use json like structure to represent data, we can populate data in a bson Document object and then simply put in collection. Let us directly turn to an example to insert document in mongodb.

Create Mongodb connection

Create mongodb connection from java program.

Retrieve Database and Collection

Mongodb driver provides the api to connect to MongoDatabase and MongoCollection. Code snippet below will connect to employee_db database and retrieve the employee collection in which we want to insert document in mongodb.

Populate Data in Document
Consider you want to insert document in mongodb as follows.

We can populate above data using java code below.

and insert document in mongodb using

I hope this article helped understand how to insert document in mongodb using java.