Categories: MongoDB

Java MongoDB Inserting a Document to Database

In this tutorial we will discussing about inserting a document to the MongoDB. There are four ways to inserting document JSON format to the MongoDB. Here in this page we are going to discuss how to insert data into a collection. The documents stored in MongoDB are JSON-like. All data stored into the collection are in BSON format.

Switch to a MongoDB database-

Here, our database is “dineshonjavaDB”.

> use dineshonjavaDB
switch to db dineshonjavaDB

1. Define a document for MongoDB database-

The following document can be stored in MongoDB.

> document=({"empId" : "10001","empName" :"Dinesh Rajput" ,"date_of_join" : "10/04/2010"
 ,"education" :"M.C.A." , "profession" : "DEVELOPER","interest" : "MUSIC","community_name"
 :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN MUSIC"],"community_moder_id" : ["MR. BBB","MR.
 JJJ","MR MMM"],"community_members" : [500,200,1500],"friends_id" : 
["MMM123","NNN123","OOO123"],"ban_friends_id" :["BAN123","BAN456","BAN789"]});

2. DBCollection.insert()- Insert a document into a collection-

To save the above document into the collection “employees” under “dineshonjavaDB” database the following command can be used –

> db.employees.insert(document) 

There are 4 Ways to insert data into MongoDB using Java API.

1. BasicDBObject example

BasicDBObject document = new BasicDBObject();
document.put("database", "dineshonjavaDB");
document.put("table", "employees");
 
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("empId", "10001");
documentDetail.put("empName", "Dinesh");
documentDetail.put("salary", "70000");
 
document.put("detail", documentDetail);
 
collection.insert(document);

2. BasicDBObjectBuilder example

BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  .add("database", "dineshonjavaDB")
  .add("table", "employees");
 
 BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
 .add("empId", "10001")
 .add("empName", "Dinesh")
 .add("salary", "70000");
 
 documentBuilder.add("detail", documentBuilderDetail.get());
 
 collection.insert(documentBuilder.get());
  • Create a new BasicDBObject and invoke its put() method to set the document attributes.
  • Create a BasicDBObjectBuilder instance (that follows the builder design pattern) by invoking the static BasicDBObjectBuilder.start() method, calling the add() method to add attributes to the document, and then invoking get() to retrieve the resultant DBObject, which is the approach I took when building the employees document

3. Map example

Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("database", "dineshonjavaDB");
documentMap.put("table", "employees");
 
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("empId", "10001");
documentMapDetail.put("empName", "Dinesh");
documentMapDetail.put("salary", "70000");

documentMap.put("detail", documentMapDetail);
 
collection.insert(new BasicDBObject(documentMap));

4. JSON parse example

String json = "{'database' : 'dineshonjavaDB','table' : 'employees'," +
 "'detail' : {'empId' : 10001, 'empName' : 'Dinesh', 'salary' : 70000}}}";

DBObject dbObject = (DBObject)JSON.parse(json);
 
collection.insert(dbObject);

Now see the full example of Inserting data into the collection

package com.dineshonjava.mongo.test;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * @author Dinesh Rajput
 *
 */
public class InsertDocumentDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
 try {
  // connect to mongoDB, IP and port number
  Mongo mongo = new Mongo("localhost", 27017);
  // get database from MongoDB,
  // if database doesn't exists, mongoDB will create it automatically
  DB db = mongo.getDB("dineshonjavaDB");
   
  // get a single collection
  DBCollection collection = db.getCollection("employees");

  // BasicDBObject example
  System.out.println("BasicDBObject example...");
  BasicDBObject document = new BasicDBObject();
  document.put("database", "dineshonjavaDB");
  document.put("table", "employees");

  BasicDBObject documentDetail = new BasicDBObject();
  documentDetail.put("empId", "10001");
  documentDetail.put("empName", "Dinesh");
  documentDetail.put("salary", "70000");
  document.put("detail", documentDetail);

  collection.insert(document);

  DBCursor cursorDoc = collection.find();
  while (cursorDoc.hasNext()) {
  System.out.println(cursorDoc.next());
  }
 
  collection.remove(new BasicDBObject());

  // BasicDBObjectBuilder example
  System.out.println("BasicDBObjectBuilder example...");
 BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
   .add("database", "dineshonjavaDB")
                        .add("table", "employees");
 
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
                    .add("empId", "10001")
                    .add("empName", "Dinesh")
           .add("salary", "70000");
 
 documentBuilder.add("detail", documentBuilderDetail.get());
 
 collection.insert(documentBuilder.get());
 
 DBCursor cursorDocBuilder = collection.find();
 while (cursorDocBuilder.hasNext()) {
  System.out.println(cursorDocBuilder.next());
 }
 
 collection.remove(new BasicDBObject());
 
 // Map example
 System.out.println("Map example...");
 Map<String, Object> documentMap = new HashMap<String, Object>();
 documentMap.put("database", "dineshonjavaDB");
 documentMap.put("table", "employees");
 
 Map<String, Object> documentMapDetail = new HashMap<String, Object>();
 documentMapDetail.put("empId", "10001");
 documentMapDetail.put("empName", "Dinesh");
 documentMapDetail.put("salary", "70000");
 
 documentMap.put("detail", documentMapDetail);
 
 collection.insert(new BasicDBObject(documentMap));
 
 DBCursor cursorDocMap = collection.find();
 while (cursorDocMap.hasNext()) {
  System.out.println(cursorDocMap.next());
 }
 
 collection.remove(new BasicDBObject());
 
 // JSON parse example
 System.out.println("JSON parse example...");
 
 String json = "{'database' : 'dineshonjavaDB','table' : 'employees'," +
 "'detail' : {'empId' : 10001, 'empName' : 'Dinesh', 'salary' : '70000'}}}";
 
 DBObject dbObject = (DBObject)JSON.parse(json);
 
 collection.insert(dbObject);
 
 DBCursor cursorDocJSON = collection.find();
 while (cursorDocJSON.hasNext()) {
  System.out.println(cursorDocJSON.next());
 }
 
 //collection.remove(new BasicDBObject());
 
 System.out.println("Done");
 
} catch (UnknownHostException e) {
   e.printStackTrace();
} catch (MongoException e) {
   e.printStackTrace();
}
 
}

}

If every thing is fine then run as Java Application then we will get the following output on the console.

output:
BasicDBObject example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84ae”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : “10001” , “empName” : “Dinesh” , “salary” : “70000”}}
BasicDBObjectBuilder example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84af”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : “10001” , “empName” : “Dinesh” , “salary” : “70000”}}
Map example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84b0”} , “detail” : { “empName” : “Dinesh” , “empId” : “10001” , “salary” : “70000”} , “table” : “employees” , “database” : “dineshonjavaDB”}
JSON parse example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84b1”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : 10001 , “empName” : “Dinesh” , “salary” : “70000”}}
Done

What is “_id” ?

 The “_id” is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with “_”, “/” and “$” are reserved for internal use.

Reference
Java tutorial – MongoDB

Download Source Code + Libs
MongoDBInsertDocumentDemo.zip

 

                             <<previous<<             || index  ||         >>next>>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago