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.
Here, our database is “dineshonjavaDB”.
> use dineshonjavaDB
switch to db dineshonjavaDB
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"]});
To save the above document into the collection “employees” under “dineshonjavaDB” database the following command can be used –
> db.employees.insert(document)
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());
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.
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
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…