In this Article, I will show How to connect to MongoDB
database from java. How to perform retrieve, insert, update
and delete operations.
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>HelloWorldExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HelloWorldExample</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");
Complete example is Here,
App.java
package com.devjavasource.mongodb.HelloWorldExample;
import java.util.Date;
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");
// Retrieve all the documents of a specified collection
retrieve(collection);
// Insert a new document into MongoDB
System.out.println("\n********MondoDB - Insert operation ******\n");
insert(collection);
retrieve(collection);
// Update a document
System.out.println("\n********MondoDB - Update operation ******\n");
update(collection);
retrieve(collection);
System.out.println("\n********MondoDB - Delete operation ******\n");
collection.deleteOne(new Document("order_id", "41704621"));
retrieve(collection);
} catch (Exception e) {
e.printStackTrace();
} finally {
mongoClient.close();
}
}
private static void update(final MongoCollection<Document> inCollection) {
inCollection.updateOne(new Document("order_id", "41704621"),
new Document("$set", new Document("status", "Executed"))
.append("$currentDate", new Document("lastModified",
true)));
}
private static void insert(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 BasicDBObject itemsDocument = new BasicDBObject();
itemsDocument.put("item_id", "Item101");
itemsDocument.put("count", 21);
itemsDocument.put("date", new Date());
document.put("Items", itemsDocument);
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();
printit(doc);
}
}
private static void printit(final Document inDoc) {
System.out.println("Order Details are:");
System.out.println("====================");
inDoc.entrySet().stream().forEach(each -> {
System.out.println("Key : " + each.getKey());
System.out.println("Value : " + each.getValue());
});
}
}
5) Demo :
Select App.java and right click “Run As” -> “Java Application”.
Order Details are:
====================
Key : _id
Value : 55e95be41293cc73ac76c899
Key : address
Value : Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}
Key : status
Value : Ordered
Key : Items
Value : [Document{{date=Wed Oct 01 05:30:00 IST 2014, item_id=Item101, count=11.0}}, Document{{date=Thu Jan 16 05:30:00 IST 2014, item_id=Item102, count=17.0}}]
Key : customer_name
Value : Rick GoldMan
Key : order_id
Value : 41704620
********MondoDB - Insert operation ******
Order Details are:
====================
Key : _id
Value : 55e95be41293cc73ac76c899
Key : address
Value : Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}
Key : status
Value : Ordered
Key : Items
Value : [Document{{date=Wed Oct 01 05:30:00 IST 2014, item_id=Item101, count=11.0}}, Document{{date=Thu Jan 16 05:30:00 IST 2014, item_id=Item102, count=17.0}}]
Key : customer_name
Value : Rick GoldMan
Key : order_id
Value : 41704620
Order Details are:
====================
Key : _id
Value : 55e966454ef0ec278cc4324e
Key : order_id
Value : 41704621
Key : customer_name
Value : Stuart Adamson
Key : status
Value : Ordered
Key : address
Value : Document{{street=13th Street, 2 Lane, zipcode=30014, building=Avenue Park}}
Key : Items
Value : Document{{item_id=Item101, count=21, date=Fri Sep 04 15:07:09 IST 2015}}
********MondoDB - Update operation ******
Order Details are:
====================
Key : _id
Value : 55e95be41293cc73ac76c899
Key : address
Value : Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}
Key : status
Value : Ordered
Key : Items
Value : [Document{{date=Wed Oct 01 05:30:00 IST 2014, item_id=Item101, count=11.0}}, Document{{date=Thu Jan 16 05:30:00 IST 2014, item_id=Item102, count=17.0}}]
Key : customer_name
Value : Rick GoldMan
Key : order_id
Value : 41704620
Order Details are:
====================
Key : _id
Value : 55e966454ef0ec278cc4324e
Key : order_id
Value : 41704621
Key : customer_name
Value : Stuart Adamson
Key : status
Value : Executed
Key : address
Value : Document{{street=13th Street, 2 Lane, zipcode=30014, building=Avenue Park}}
Key : Items
Value : Document{{item_id=Item101, count=21, date=Fri Sep 04 15:07:09 IST 2015}}
Key : lastModified
Value : Fri Sep 04 15:07:09 IST 2015
********MondoDB - Delete operation ******
Order Details are:
====================
Key : _id
Value : 55e95be41293cc73ac76c899
Key : address
Value : Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}
Key : status
Value : Ordered
Key : Items
Value : [Document{{date=Wed Oct 01 05:30:00 IST 2014, item_id=Item101, count=11.0}}, Document{{date=Thu Jan 16 05:30:00 IST 2014, item_id=Item102, count=17.0}}]
Key : customer_name
Value : Rick GoldMan
Key : order_id
Value : 41704620
Download the source code
You can download the source code here: HelloWorldExample
*** Venkat – Happy leaning ****
