Java MongoDB : Insert a document

In this tutorial we will see how to insert a document in mongodb using java driver. To create the document using the Java driver, we use the Document class.   In this example we will also create an embedded document.

Tools used

  1. mongo java driver : 3.3.0
  2. mongodb : 3.2.8
  3. maven : 3
  4. java : 1.7

Maven dependency

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

 

Data for the example

{
   "name" : "Obama",
   "type" : "person",  
   "address" : {
               "city" : "Washington",
                "zip" : 20500
             }
}

Example


package com.programtalk.example.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class InsertDocumentExample {
	private final static String DB_NAME = "testdb";

	private final static String PERSONS = "persons";

	public static void main(String[] args) {
		MongoClient mongoClient = new MongoClient();
		MongoDatabase database = mongoClient.getDatabase(DB_NAME);
		MongoCollection&lt;Document&gt; personsCollection = database.getCollection(PERSONS);
		Document obama = new Document("name", "Obama")
	               .append("type", "person")
	               .append("address", new Document("city", "Washington").append("zip", 20500));
		personsCollection.insertOne(obama);
		
		Document myDoc = personsCollection.find().first();
		System.out.println(myDoc.toJson());
		mongoClient.close();
	}

}

Output


{ "_id" : { "$oid" : "57b9e9607ec94d155848fec6" }, "name" : "Obama", "type" : "person", "address" : { "city" : "Washington", "zip" : 20500 } }

Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *