<div dir="ltr" style="text-align: justify;">
<p>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.</p>
<h2>Switch to a MongoDB database-</h2>
<p>Here, our database is &#8220;dineshonjavaDB&#8221;.</p>
<p>>; use dineshonjavaDB<br />
switch to db dineshonjavaDB</p>
<h2><b>1. Define a document for MongoDB database-</b></h2>
<p>The following document can be stored in MongoDB.</p>
<pre class="highlight">>; 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"]}); 
</pre>
<p><img class="aligncenter" src="https://dineshonjava.com/wp-content/uploads/2013/01/documentd.png" alt="Java MongoDB Inserting a Document to Database" border="0" /></p>
<h2><b>2. DBCollection.insert()- Insert a document into a collection-</b></h2>
<p>To save the above document into the collection &#8220;employees&#8221; under &#8220;dineshonjavaDB&#8221; database the following command can be used &#8211;</p>
<pre class="highlight">>; db.employees.insert(document) 
</pre>
<p><img class="aligncenter" src="https://dineshonjava.com/wp-content/uploads/2013/01/document.png" alt="MongoDB Inserting a Document to Database" border="0" /></p>
<h2><i><b>There are </b><b>4 Ways to insert data into MongoDB using Java API.</b></i></h2>
<p><b>1. BasicDBObject example</b></p>
<pre class="highlight">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); 
</pre>
<div id="ads-id" align="center"></div>
<p><b>2. BasicDBObjectBuilder example</b></p>
<pre class="highlight">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()); 
</pre>
<ul>
<li>Create a new BasicDBObject and invoke its put() method to set the document attributes<b>.</b></li>
<li>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</li>
</ul>
<p><b>3. Map example</b></p>
<pre class="highlight">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)); 
</pre>
<p><b>4. JSON parse example</b></p>
<pre class="highlight">String json = "{'database' : 'dineshonjavaDB','table' : 'employees'," + 
 "'detail' : {'empId' : 10001, 'empName' : 'Dinesh', 'salary' : 70000}}}"; 
 
DBObject dbObject = (DBObject)JSON.parse(json); 
 
collection.insert(dbObject); 
</pre>
<p>Now see the full example of Inserting data into the collection</p>
<pre class="highlight">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(); 
} 
 
} 
 
} 
</pre>
<p>If every thing is fine then run as Java Application then we will get the following output on the console.</p>
<div style="background-color: #ff99cc;"><b>output:</b><br />
BasicDBObject example&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;5104d7cc37de7e0a362e84ae&#8221;} , &#8220;database&#8221; : &#8220;dineshonjavaDB&#8221; , &#8220;table&#8221; : &#8220;employees&#8221; , &#8220;detail&#8221; : { &#8220;empId&#8221; : &#8220;10001&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : &#8220;70000&#8221;}}<br />
BasicDBObjectBuilder example&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;5104d7cc37de7e0a362e84af&#8221;} , &#8220;database&#8221; : &#8220;dineshonjavaDB&#8221; , &#8220;table&#8221; : &#8220;employees&#8221; , &#8220;detail&#8221; : { &#8220;empId&#8221; : &#8220;10001&#8221; , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : &#8220;70000&#8221;}}<br />
Map example&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;5104d7cc37de7e0a362e84b0&#8221;} , &#8220;detail&#8221; : { &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;empId&#8221; : &#8220;10001&#8221; , &#8220;salary&#8221; : &#8220;70000&#8221;} , &#8220;table&#8221; : &#8220;employees&#8221; , &#8220;database&#8221; : &#8220;dineshonjavaDB&#8221;}<br />
JSON parse example&#8230;<br />
{ &#8220;_id&#8221; : { &#8220;$oid&#8221; : &#8220;5104d7cc37de7e0a362e84b1&#8221;} , &#8220;database&#8221; : &#8220;dineshonjavaDB&#8221; , &#8220;table&#8221; : &#8220;employees&#8221; , &#8220;detail&#8221; : { &#8220;empId&#8221; : 10001 , &#8220;empName&#8221; : &#8220;Dinesh&#8221; , &#8220;salary&#8221; : &#8220;70000&#8221;}}<br />
Done</div>
<h2><i><b>What is &#8220;_id&#8221; ?</b></i></h2>
<p><i><b> </b></i><b>The &#8220;_id&#8221; is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with &#8220;_&#8221;, &#8220;/&#8221; and &#8220;$&#8221; are reserved for internal use.</b></p>
<p><b>Reference</b><br />
<a href="http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-GettingACollection" target="_blank" rel="noopener">Java tutorial – MongoDB</a></p>
<h2><b>Download Source Code + Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBInsertDocumentDemo.zip?attredirects=0&;d=1" target="_blank" rel="noopener">MongoDBInsertDocumentDemo.zip </a></h2>
<p> ;</p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/java-mongodb-get-collection-from/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/java-mongodb-deleting-document-to/">next</a>>;>;</b></div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/java-mongodb-get-collection-from/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/java-mongodb-deleting-document-to/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '591'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…