Insert Document in MongoDB using Java

In this example, We will show you the simple program about, How to insert document in MongoDB using Java. The example were tested with mongodb server 3.4.2 environment and output shared in the same post.

Test Input Document

{
"firstName":"Dinesh",
"lastName":"Krishnan",
"fullName":"Dinesh Krishnan",
"age":27,
"country":"India",
"skills": {
"java":["Java", "J2EE", "Spring", "Hibernate", "Struts", "AKKA"],
"ui":["HTML", "CSS", "JS", "Angular JS", "JQuery", "AJAX"]
}
}

Example Program

package com.dineshkrish.mongo;
import org.bson.Document;
import com.mongodb.BasicDBList;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* 
* @author Dinesh Krishnan
*
*/
public class InsertDocument {
public static void main(String[] args) {
// getting the connection
MongoClient client = new MongoClient("localhost", 27017);
// selecting the database
MongoDatabase database = client.getDatabase("dineshkrish");
// selecting the collection
MongoCollection<Document> collection = database.getCollection("employee");
// creating the document object
Document rootObj = new Document();
rootObj.put("firstName", "Dinesh");
rootObj.put("lastName", "Krishnan");
rootObj.put("fullName", "Dinesh Krishnan");
rootObj.put("age", 27);
rootObj.put("country", "India");
// adding the skills
BasicDBList javaSkils = new BasicDBList();
javaSkils.add("Java");
javaSkils.add("J2EE");
javaSkils.add("Spring");
javaSkils.add("Hibernate");
javaSkils.add("Struts");
javaSkils.add("AKKA");
// adding the skills
BasicDBList uiSkils = new BasicDBList();
uiSkils.add("HTML");
uiSkils.add("CSS");
uiSkils.add("Java Script");
uiSkils.add("JQuery");
uiSkils.add("AJAX");
uiSkils.add("Angular JS");
Document skilsObj = new Document();
skilsObj.put("java", javaSkils);
skilsObj.put("ui", uiSkils);
rootObj.put("skills", skilsObj);
// inserting the document
collection.insertOne(rootObj);
// closing the connection
client.close();
}
}

Output

How to Insert Document in MongoDB using Java

References

1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
4. JavaDoc – Document Class
5. JavaDoc – BasicDBList Class

No responses yet

Leave a Reply

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