In this Article, I will show different ways of inserting
document into MongoDB database.
Tools used :
1) eclipse version Luna 4.4.1.
2) Maven 3.3.3
3) MongoDB 3.0.6 Server.
4) mongo-java-driver 3.0.2.
5) Java 1.8
If you are completely new to mongodb,
please refer mongodb-quick-start
Prerequisites :
1) mongodb Server should be up and running.
2) collection should be created with name “devJavaSource”
Steps to be followed :
1) Create a maven project in eclipse.
2) Add MongoDB java driver dependency to pom.xml file.
3) Start MongoDB server.
4) Write a simple java program.
5) Demo.
Add mongoDB dependency to pom.xml :
MongoDB java driver is required to run java program.
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.0.2</version> </dependency>
Complete pom.xml is Here,
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.devjavasource.mongodb</groupId> <artifactId>insertOperation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>insertOperation</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.0.2</version> </dependency> </dependencies> </project>
3) Start MongoDB server :
Go to C:\mongodb\bin> monngod.exe is the command to start MongoDB server.
4) Write a simple java program :
To get Database connection, create a MongoClient instance and call getDatabase()
method to get database connection to the particular database.
Connect to the local database running on the default port.
MongoClient mongoClient = null; // Get MongoClient Connect to MongoDB mongoClient = new MongoClient("localhost", 27017); // Get database // If database doesn't exists, MongoDB will create it for you MongoDatabase db = mongoClient.getDatabase("devjavasource");
Insert Operation :
We can insert json object data into mongodb in Three ways.
1) Basic Insert Operation :
This is pretty simple, we need to create a Document object
and put all the key and values into and pass this document object
to insertOne() method of collection.
final MongoCollection<Document> collection = db.getCollection("orders"); final Document document = new Document(); document.put("order_id", "41704621"); document.put("customer_name", "Stuart Adamson"); document.put("status", "Ordered"); final BasicDBObject addressDocument = new BasicDBObject(); addressDocument.put("street", "13th Street, 2 Lane"); addressDocument.put("zipcode", "30014"); addressDocument.put("building", "Avenue Park"); document.put("address", addressDocument); // Here list of maps is required, As the items is json list final List
3) Insert – Using Map Object :
Create a Map object and put all key and values into map.
Create a Document object by passing the map as an argument and
pass this document object to insertOne() method of collections
to insert document into db.
final MongoCollection<Document> collection = db.getCollection("orders"); final Map<String, Object> map = new HashMap<>(); map.put("customer_name", "Mint Shah"); map.put("order_id", "41704623"); map.put("status", "Ordered"); final Map<String, Object> addressMap = new HashMap<>(); addressMap.put("street", "23th Street, 2 Lane"); addressMap.put("zipcode", "11014"); addressMap.put("building", "Millet Avenue"); map.put("address", addressMap); final List<Map<String, Object>> itemList = new ArrayList<>(); final Map<String, Object> item = new HashMap<>(); item.put("date", new Date()); item.put("item_id", "Item101"); item.put("count", 9); itemList.add(item); map.put("Items", itemList); collection.insertOne(new Document(map));
3) Insert – Using JSON parser :
Given is the Data that to be inserted
into database using Map object,
{ "address" : { "street" : "23th Street, 2 Lane", "zipcode" : "11014", "building" : "Millet Avenue" }, "status" : "Ordered", "Items" : [ { "date" : ISODate("Mon Sep 14 15:25:50 IST 2015"), "item_id" : "Item101", "count" : 9 } ], "customer_name" : "Mint Shah", "order_id" : "41704623" }
Create json object in String format and pass this string object to parse method of
Document class and pass the resulted document object to insertOne() method
of collection object.
final MongoCollection<Document> collection = db.getCollection("orders"); final String strJson = "{ 'address' : { 'street' : '3th Street, 12 Lane', 'zipcode' : '20014', 'building' : 'Milton Avenue' }, " + "'status' : 'Ordered', 'Items' : [ { 'date' : '1442295544009', 'item_id' : 'Item102', " + "'count' : 16 } ], 'customer_name' : 'Jhon Scatter hood', 'order_id' : '41704622'}"; collection.insertOne(Document.parse(strJson));
Complete example is Here,
App.java
package com.devjavasource.mongodb; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bson.Document; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class App { public static void main(String[] args) { MongoClient mongoClient = null; try { // Get MongoClient Connect to MongoDB mongoClient = new MongoClient("localhost", 27017); // Get database // If database doesn't exists, MongoDB will create it for you MongoDatabase db = mongoClient.getDatabase("devjavasource"); // Get collection / table from 'devjavasource' // If collection doesn't exists, MongoDB will create it for you MongoCollection<Document> collection = db.getCollection("orders"); // Insert a new document into MongoDB System.out.println("\n********MondoDB - Insert operation ******\n"); System.out.println("Basic Insert Operation ...."); basicInsert(collection); retrieve(collection); // Insert - Using Map Object System.out.println("\nInsert - Using Map Object...."); mapInsert(collection); retrieve(collection); // Insert - Using JSON parser System.out.println("\nInsert - Using JSON parser...."); jsonInsert(collection); retrieve(collection); } catch (Exception e) { e.printStackTrace(); } finally { mongoClient.close(); } } private static void mapInsert(final MongoCollection<Document> inCollection) { final Map<String, Object> map = new HashMap<>(); map.put("customer_name", "Mint Shah"); map.put("order_id", "41704623"); map.put("status", "Ordered"); final Map<String, Object> addressMap = new HashMap<>(); addressMap.put("street", "23th Street, 2 Lane"); addressMap.put("zipcode", "11014"); addressMap.put("building", "Millet Avenue"); map.put("address", addressMap); final List<Map<String, Object>> itemList = new ArrayList<>(); final Map<String, Object> item = new HashMap<>(); item.put("date", new Date()); item.put("item_id", "Item101"); item.put("count", 9); itemList.add(item); map.put("Items", itemList); inCollection.insertOne(new Document(map)); } private static void jsonInsert(final MongoCollection<Document> inCollection) { final String strJson = "{ 'address' : { 'street' : '3th Street, 12 Lane', 'zipcode' : '20014', 'building' : 'Milton Avenue' }, " + "'status' : 'Ordered', 'Items' : [ { 'date' : '1442295544009', 'item_id' : 'Item102', " + "'count' : 16 } ], 'customer_name' : 'Jhon Scatter hood', 'order_id' : '41704622'}"; inCollection.insertOne(Document.parse(strJson)); } private static void basicInsert(final MongoCollection<Document> inCollection) { final Document document = new Document(); document.put("order_id", "41704621"); document.put("customer_name", "Stuart Adamson"); document.put("status", "Ordered"); final BasicDBObject addressDocument = new BasicDBObject(); addressDocument.put("street", "13th Street, 2 Lane"); addressDocument.put("zipcode", "30014"); addressDocument.put("building", "Avenue Park"); document.put("address", addressDocument); final List<Map<String, Object>> itemList = new ArrayList<>(); final Map<String, Object> item = new HashMap<>(); item.put("item_id", "Item101"); item.put("count", 21); item.put("date", new Date()); itemList.add(item); document.put("Items", itemList); inCollection.insertOne(document); } private static void retrieve(final MongoCollection<Document> inCollection) { final FindIterable<Document> itr = inCollection.find(); final MongoCursor<Document> mongoItr = itr.iterator(); while (mongoItr.hasNext()) { final Document doc = mongoItr.next(); System.out.println(doc.toJson()); inCollection.deleteOne(doc); } } }
5) Demo :
Select App.java and right click “Run As” -> “Java Application”.
********MondoDB - Insert operation ****** Basic Insert Operation .... { "_id" : { "$oid" : "55f809bc5f1a8c32988928a8" }, "order_id" : "41704621", "customer_name" : "Stuart Adamson", "status" : "Ordered", "address" : { "s treet" : "13th Street, 2 Lane", "zipcode" : "30014", "building" : "Avenue Park" }, "Items" : [{ "date" : { "$date" : 1442318780178 }, "item_id" : "Ite m101", "count" : 21 }] } Insert - Using Map Object.... { "_id" : { "$oid" : "55f809bc5f1a8c32988928a9" }, "address" : { "zipcode" : "11014", "street" : "23th Street, 2 Lane", "building" : "Millet Avenue" } , "Items" : [{ "date" : { "$date" : 1442318780248 }, "item_id" : "Item101", "count" : 9 }], "customer_name" : "Mint Shah", "order_id" : "41704623", "s tatus" : "Ordered" } Insert - Using JSON parser.... { "_id" : { "$oid" : "55f809bc5f1a8c32988928aa" }, "address" : { "street" : "3th Street, 12 Lane", "zipcode" : "20014", "building" : "Milton Avenue" } , "status" : "Ordered", "Items" : [{ "date" : "1442295544009", "item_id" : "Item102", "count" : 16 }], "customer_name" : "Jhon Scatter hood", "order_i d" : "41704622" }
Download the source code
You can download the source code here: MongoDBOperations
*** Venkat – Happy leaning ****