Java Connecting to MongoDB 3.2 Examples

Java Connecting to MongoDB 3.2 Examples

In this tutorial, Java Connecting to MongoDB 3.2 Examples we will show you different ways to connect to the latest version of MongoDB using Java and their mongo java driver (mongo-java-driver-3.2.0.jar).

What is MongoDB?

MongoDB is a open-source document-oriented database written in C++ and C and licensed under the GNU Affero General Public License and the Apache Licenses. It is classified as a NoSQL database using JSON-like formatted documents for the data model. Although there are several other NoSQL databases on the market today, mongoDB is by far, the most popular one.

Download MongoDB

MongoDB offers several binary distributions, both in 32 & 64-bit flavors for various operating systems. They currently support multiple operating systems including Windows, Linux, Mac OS X, and Solaris OS. MongoDB may be found at the following URL: https://www.mongodb.org/downloads or from their main website click the on downloads link. The Java Driver for MongoDB can be found in Maven Repository at URL: http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/3.2.0

What’s Covered

  1. Connecting to MongoDB Server using MongoClient
  2. Connecting to MongoDB Server, creating Replica Sets
  3. Deprecated Methods in MongoDB 3.2 (DB, DBCollection, DBCursor)
  4. Using MongoDatabase Method in MongoDB 3.2
  5. Using MongoCollection Method in MongoDB 3.2
  6. Using MongoCursor Method in MongoDB 3.2
  7. Performing Basic Inserts in MongoDB
  8. Performing Inserts using Map in MongoDB
  9. Performing Inserts using JSON in MongoDB
  10. Using For Loop with Collection in MongoDB 3.2

Getting Started

In order to run this tutorial yourself, you will need the following:

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
mongo-java-driver-3.2.0.jar

Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

mongodb_connection_proj_struct

Connecting to MongoDB Server using MongoClient

MongoClient is used to make a connection to MongoDB server. MongoClient has built-in connection pooling for added speed improvements. Note: Only one MongoClient instance per JVM. There are various flavors that may be used:

MongoClient mongoClient = new MongoClient();

OR

MongoClient mongoClient = new MongoClient("localhost");

OR

MongoClient mongoClient = new MongoClient("localhost", 27017);

OR

MongoClient mongoClient = new MongoClient(
                  new ServerAddress("db.avaldes.com"), 29019);

OR

Pass a list of ServerAddress, to create a replica set using the Java driver in the MongoClient constructor.

MongoClient mongoClient = new MongoClient(Arrays.asList(
                  new ServerAddress("db.avaldes.com"), 27017),
                  new ServerAddress("db.avaldes.com"), 27018)
                  new ServerAddress("db.avaldes.com"), 27019)));

OR use a Connection String composed of the following: mongodb://[username:password@]host1[:port1][,host2[:port2]]…[/[database][?options]

In this example, i am connecting to the database named admin, server named db1.avaldes.com on port 27017, using the username root and a password root123.

MongoClientURI uri = new MongoClientURI(
          "mongodb://root:root123@db1.avaldes.com:27017/?authSource=admin");
MongoClient mongoClient = new MongoClient(uri);

Connecting to MongoDB Database using DB

A thread-safe client view of a logical database in a MongoDB database. A MongoDB database may have one or more collections. A collection is the equivalent of a database table in a standard Relational Database Management System (RDBMS). The main difference between collections and tables is that in MongoDB the documents that are stored in the collections do NOT conform to any given schema. So it is very possible to have some documents containing certain fields and other documents to be missing these given fields.

Deprecated Methods in MongoDB 3.2

This version effectively deprecates the DB, DBCollection, and DBCursor classes, among others; but Mongo folks have decided to give users some time to migrate to the new API without experiencing a huge number of compiler warnings. To that end, those classes have not yet been formally deprecated.
MongoClient mongoClient = null;
    
try {
  mongoClient = new MongoClient();
  
  // Old way to get database - deprecated now
  DB db = mongoClient.getDB("test");  
  
  // Old way to get collection - deprecated now
  DBCollection collection = db.getCollection("employee");
  System.out.println("collection: " + collection);
} catch (Exception e) {
  e.printStackTrace();
} finally{
  mongoClient.close();
}

New Superceded Methods in MongoDB 3.2

The newer classes are MongoDatabase, MongoCollection, and MongoCursor.
MongoClient mongoClient = null;
    
try {
  mongoClient = new MongoClient();
  
  // New way to get database
  MongoDatabase db = mongoClient.getDatabase("test");
  
  // New way to get collection
  MongoCollection<Document> collection = db.getCollection("employee");
  System.out.println("collection: " + collection);
} catch (Exception e) {
  e.printStackTrace();
} finally{
  mongoClient.close();
}

Performing Basic Inserts in MongoDB

In this example, note that we create a BasicDBObject and then put key/value pairs for each of the elements in the document before we insert it into the MongoDB collection.

System.out.println("Inserting using BasicDBObjects...");
BasicDBObject basic1 = new BasicDBObject();
basic1.put("_id", "1");
basic1.put("type", "basic");
basic1.put("first-name", "Amaury");
basic1.put("last-name", "Valdes");    
collection.insert(basic1);
System.out.println("Employee 1: " + basic1.toJson());

BasicDBObject basic2 = new BasicDBObject();
basic2.put("_id", "2");
basic2.put("type", "basic");
basic2.put("first-name", "Jane");
basic2.put("last-name", "Valdes");    
collection.insert(basic2);
System.out.println("Employee 2: " + basic2.toJson());
employee_test_example

Using DBCursor — Deprecated Method in MongoDB 3.2

The DBCursor class like it newer equivalent MongoCursor allows you to iterate over database results by lazily fetching data from the database.

You are allowed to convert a DBCursor to an array. However, please ensure that your results are limited in scope as the cursor may have been iterating over thousands or even millions of results, causing our list to contain millions of elements in memory. You should try to limit the results using skip() and limit() operators.

List employeeList = collection.find( query ).skip(100).limit( 1000 ).toArray();

DBCursor cursor = (DBCursor) collection.find().iterator();
try {
  while (cursor.hasNext()) {
    System.out.println(cursor.next().toString());
  }
} finally {
  cursor.close();
}

Using MongoCursor Method in MongoDB 3.2

MongoCursor<Document> cursor = collection.find().iterator();
try {
	while (cursor.hasNext()) {
		System.out.println(cursor.next().toJson());
	}
} finally {
	cursor.close();
}

Using For Loop with Collection in MongoDB 3.2

for (Document doc: collection.find()) {
	System.out.println(doc.toJson());
}

Performing Inserts using Map in MongoDB

In this example, we create a Map<String, Object> and put all the key/values into the Map. We insert a document and pass the Map to the constructor.

//---Insert using Map Employee #1---
final Map<String,Object> empMap1 = new HashMap<String, Object>();
empMap1.put("_id", "101");
empMap1.put("type", "map");
empMap1.put("first-name", "Stephen");
empMap1.put("last-name", "Murphy");

System.out.println("Employee: 101" + empMap1);
collection.insertOne(new Document(empMap1));

//---Insert using Map Employee #2---
final Map<String,Object> empMap2 = new HashMap<String, Object>();
empMap2.put("_id", "102");
empMap2.put("type", "map");
empMap2.put("first-name", "Harold");
empMap2.put("last-name", "Jansen");

System.out.println("Employee: 102" + empMap2);
collection.insertOne(new Document(empMap2));

Performing Inserts using JSON in MongoDB

In this example, we create a using an Employee Object and using Jackson ObjectMapper we convert it to JSON. We use this JSON string and using the Document class parse it before inserting it into MongoDB.

//---Employee #1---
final Employee employee1 = new Employee();
employee1.setEmployeeId("1001");
employee1.setType("json");
employee1.setFirstName("Jacob");
employee1.setLastName("Matthews");
 
// Use Jackson to convert Object to JSON String
mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString(employee1);
 
// Insert JSON into MongoDB
System.out.println("Employee #1001: " + jsonString);
doc = Document.parse(jsonString);
collection.insertOne(doc);
 
//---Employee #2---
final Employee employee2 = new Employee();
employee2.setEmployeeId("1002");
employee2.setType("json");
employee2.setFirstName("Allison");
employee2.setLastName("Jones");
 
// Use Jackson to convert Object to JSON String
mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString(employee2);
 
// Insert JSON into MongoDB
System.out.println("Employee #1002: " + jsonString);
doc = Document.parse(jsonString);
collection.insertOne(doc);

//---Employee #3---
final Employee employee3 = new Employee();
employee3.setEmployeeId("1003");
employee3.setType("json");
employee3.setFirstName("Debbie");
employee3.setLastName("Richards");
 
// Use Jackson to convert Object to JSON String
mapper = new ObjectMapper();
jsonString = mapper.writeValueAsString(employee3);

// Insert JSON into MongoDB
System.out.println("Employee #1003: " + jsonString);
doc = Document.parse(jsonString);
collection.insertOne(doc);
employee_test_example1

The Complete Program (MongoDBTestExample.java)

package com.avaldes.tutorial;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.bson.Document;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.avaldes.model.Employee;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDBTestExample {

  public static void main(String[] args) {
    mongoOldMethods();
    mongoTestNewMethods();
    mongoTestAuthentication();
  }
  
  public static void mongoOldMethods() {
    MongoClient mongoClient = null;
    
    try {
      System.out.println("Connecting using mongoOldMethods()...");
      mongoClient = new MongoClient();
      
      // Old way to get database - deprecated now
      DB db = mongoClient.getDB("test");

      DBCollection collection = db.getCollection("employee");
      System.out.println("collection: " + collection);
      
      System.out.println("Inserting using BasicDBObjects...");
      final BasicDBObject basic1 = new BasicDBObject();
      basic1.put("_id", "1");
      basic1.put("type", "basic");
      basic1.put("first-name", "Amaury");
      basic1.put("last-name", "Valdes");    
      collection.insert(basic1);
      System.out.println("Employee 1: " + basic1.toJson());
      
      final BasicDBObject basic2 = new BasicDBObject();
      basic2.put("_id", "2");
      basic2.put("type", "basic");
      basic2.put("first-name", "Jane");
      basic2.put("last-name", "Valdes");    
      collection.insert(basic2);
      System.out.println("Employee 2: " + basic2.toJson());
      
      showAllDocs(collection);
    } catch (Exception e) {
      e.printStackTrace();
    } finally{
      mongoClient.close();
    }
  }
  
  public static void mongoTestNewMethods() {    
    MongoClient mongoClient = null;
    
    try {
      System.out.println(
					"Connecting using mongoTestNewMethods() to 'test' database...");
      mongoClient = new MongoClient();
      MongoDatabase db = mongoClient.getDatabase("test");

      MongoCollection<Document> collection = db.getCollection("employee");
      System.out.println("Inserting using Map...");
      
      //---Insert using Map Employee #1---
      final Map<String,Object> empMap1 = new HashMap<String, Object>();
      empMap1.put("_id", "101");
      empMap1.put("type", "map");
      empMap1.put("first-name", "Stephen");
      empMap1.put("last-name", "Murphy");
      
      System.out.println("Employee: 101" + empMap1);
      collection.insertOne(new Document(empMap1));
      
      //---Insert using Map Employee #2---
      final Map<String,Object> empMap2 = new HashMap<String, Object>();
      empMap2.put("_id", "102");
      empMap2.put("type", "map");
      empMap2.put("first-name", "Harold");
      empMap2.put("last-name", "Jansen");
      
      System.out.println("Employee: 102" + empMap2);
      collection.insertOne(new Document(empMap2));
      
      //Show all documents in the collection
      showAllDocuments(collection);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      mongoClient.close();
    }
  }
  
  public static void mongoTestAuthentication(){
    String jsonString;
    Document doc;
    ObjectMapper mapper;    
    MongoClient mongoClient = null;
    
    try {
      System.out.println("Connecting using mongoTestAuthentication() 
				to 'secured' database...");
      MongoClientURI uri = new MongoClientURI(
					"mongodb://root:root123@localhost:27017/?authSource=admin");
      mongoClient = new MongoClient(uri);
      
      MongoDatabase db = mongoClient.getDatabase("secured");

      MongoCollection<Document> collection = db.getCollection("employee");
      System.out.println("Inserting using Jackson Object->JSON...");
      
      //---Employee #1---
      final Employee employee1 = new Employee();
      employee1.setEmployeeId("1001");
      employee1.setType("json");
      employee1.setFirstName("Jacob");
      employee1.setLastName("Matthews");
      
      // Use Jackson to convert Object to JSON String
      mapper = new ObjectMapper();
      jsonString = mapper.writeValueAsString(employee1);
      
      // Insert JSON into MongoDB
      System.out.println("Employee #1001: " + jsonString);
      doc = Document.parse(jsonString);
      collection.insertOne(doc);
      
      //---Employee #2---
      final Employee employee2 = new Employee();
      employee2.setEmployeeId("1002");
      employee2.setType("json");
      employee2.setFirstName("Allison");
      employee2.setLastName("Jones");
      
      // Use Jackson to convert Object to JSON String
      mapper = new ObjectMapper();
      jsonString = mapper.writeValueAsString(employee2);
      
      // Insert JSON into MongoDB
      System.out.println("Employee #1002: " + jsonString);
      doc = Document.parse(jsonString);
      collection.insertOne(doc);

      //---Employee #3---
      final Employee employee3 = new Employee();
      employee3.setEmployeeId("1003");
      employee3.setType("json");
      employee3.setFirstName("Debbie");
      employee3.setLastName("Richards");
      
      // Use Jackson to convert Object to JSON String
      mapper = new ObjectMapper();
      jsonString = mapper.writeValueAsString(employee3);
    
      // Insert JSON into MongoDB
      System.out.println("Employee #1003: " + jsonString);
      doc = Document.parse(jsonString);
      collection.insertOne(doc);
    
      //Show all documents in the collection
      showAllDocuments(collection);
    } catch (JsonGenerationException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      mongoClient.close();
    }
  }
  
  public static void showAllDocuments( 
												final MongoCollection<Document> collection) {
													
    System.out.println("----[Retrieve All Documents in Collection]----");
    for (Document doc: collection.find()) {
      System.out.println(doc.toJson());
    }
  }
  
  public static void showAllDocs(final DBCollection collection) {
    DBCursor cursor = (DBCursor) collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toString());
        }
    } finally {
        cursor.close();
    }
  }
}

Testing out our MongoDBTestExample Application

Connecting using mongoOldMethods()...

Inserting using BasicDBObjects...
Employee 1: { "_id" : "1", "type" : "basic", "first-name" : "Amaury", 
							"last-name" : "Valdes" }
Employee 2: { "_id" : "2", "type" : "basic", "first-name" : "Jane", 
							"last-name" : "Valdes" }

Connecting using mongoTestNewMethods() to 'test' database...

Inserting using Map...
Employee: 101{_id=101, first-name=Stephen, last-name=Murphy, type=map}
Employee: 102{_id=102, first-name=Harold, last-name=Jansen, type=map}

----[Retrieve All Documents in Collection]----
{ "_id" : "1", "type" : "basic", "first-name" : "Amaury", 
	"last-name" : "Valdes" }
{ "_id" : "2", "type" : "basic", "first-name" : "Jane", 
	"last-name" : "Valdes" }
{ "_id" : "101", "first-name" : "Stephen", "last-name" : 
	"Murphy", "type" : "map" }
{ "_id" : "102", "first-name" : "Harold", "last-name" : 
	"Jansen", "type" : "map" }

Connecting using mongoTestAuthentication() to 'secured' database...

Inserting using Jackson Object->JSON...
Employee #1001: {"type":"json","_id":"1001","first-name":"Jacob",
									"last-name":"Matthews"}
Employee #1002: {"type":"json","_id":"1002","first-name":"Allison",
									"last-name":"Jones"}
Employee #1003: {"type":"json","_id":"1003","first-name":"Debbie",
									"last-name":"Richards"}

----[Retrieve All Documents in Collection]----
{ "_id" : "1001", "type" : "json", "first-name" : "Jacob", 
					"last-name" : "Matthews" }
{ "_id" : "1002", "type" : "json", "first-name" : "Allison", 
					"last-name" : "Jones" }
{ "_id" : "1003", "type" : "json", "first-name" : "Debbie", 
					"last-name" : "Richards" }

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_connect_mongodb

Related Spring Posts

  • Creating Hello World Application using Spring MVC on Eclipse IDE
    In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program.
  • Spring MVC Form Handling Example
    The following tutorial will guide you on writing a simple web based application which makes use of forms using Spring Web MVC framework. With this web application you will be able to interact with the customer entry form and enter all of the required values and submit them to the backend processes. I have taken the liberty of using CSS to beautify and transform the HTML page from a standard drab look and feel to a more appealing view.
  • Spring @RequestHeader Annotation Example
    In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.
  • Spring MVC Exception Handling using @ExceptionHandler with AngularJS GUI
    Good exception handling is a essential part of any well developed Application Framework and Spring MVC is no exception — pardon the pun. Spring MVC provides several different ways to handle exceptions in our applications. In this tutorial, we will cover Controller Based Exception Handling using the @ExceptionHandler annotation above the method that will handle it.
  • Spring RESTful Web Service Example with JSON and Jackson using Spring Tool Suite
    For this example, I will be using Spring Tool Suite (STS) as it is the best integrated development environment for building the Spring framework projects. Spring is today's leading framework for building Java, Enterprise Edition (Java EE) applications. One additional feature that makes Spring MVC so appealing is that it now also supports REST (REpresentational State Transfer) for build Web Services.
  • Spring MVC RESTful Web Service Example with Spring Data for MongoDB and ExtJS GUI
    This post will show another example of how to build a RESTful web service using Spring MVC 4.0.6, Spring Data for MongoDB 1.6.1 so that we can integrate the web application with a highly efficient datastore (MongoDB 2.6). In this tutorial we will walk you through building the web service and NoSQL database backend and show you how to implement CRUD (Create, Read, Update and Delete) operations.
  • Building DHTMLX Grid Panel User Interface with Spring MVC Rest and MongoDB Backend
    In this tutorial we will show how easy it is to use DHTMLX dhtmlxGrid component while loading JSON data with Ajax pulling in data from the Spring MVC REST web service from our MongoDB data source. You will see how simple it is to create a visually appealing experience for your client(s) with minimal javascript coding.
  • Spring MVC with JNDI Datasource for DB2 on AS/400 using Tomcat
    In this tutorial we will discuss how to set up Spring MVC web services and configure a JNDI Datasource using Tomcat and connect to IBM DB2 Database on a AS/400. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • Java Spring MVC Email Example using Apache Velocity
    In this tutorial we will discuss how to set up a Java Spring MVC RESTful Webservice with Email using Apache Velocity to create a Velocity template that is used to create an HTML email message and embed an image, as shown below, using MIME Multipart Message.
  • Implementing Basic and Advanced Search using Angular Material Design, Grid-UI, Spring MVC REST API and MongoDB Example
    In this tutorial we will discuss how to implement basic and advanced search techniques in MongoDB using AngularJS and Google’s Material Design with Spring MVC REST API backend. The advanced search user interface (UI) will use logical operators and build a JSON object which contains the search field name, boolean or logical operator and the search value.
  • Spring MVC Interceptor using HandlerInterceptorAdapter Example
    In this tutorial we will discuss how to use the HandlerInterceptorAdapter abstract class to create a Spring MVC interceptor. These interceptors are used to apply some type of processing to the requests either before, after or after the complete request has finished executing.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *