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.
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