Getting Started MongoDB with Java


MongoDB Java Driver is the officially supported Java driver for MongoDB. This guide provides instructions to get you started MongoDB with java. For new users, it's important to know an overview of how to work with the MongoDB Java driver and how to use MongoDB as a Java developer.

First, we are going to set up project/IDE to use the MongoDB Java Driver. These days IDEs tend to pick up the correct dependencies through Gradle or Maven configuration, so I'm just going to cover configuring these.

Maven dependency for MongoDB driver for java

<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongo-java-driver</artifactId>
	<version>2.12.3</version>
</dependency>

Alternatively, if you're setting jar manually to classpath, you can always download the JAR file

Connecting via Java

Now we are ready to connect MongoDB from Java application. MongoDB is a document database, so we don't connect to it via traditional SQL/relational DB methods like JDBC.

MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

If you're connecting to a local instance on the default port, you can simply use:
MongoClient mongoClient = new MongoClient();

The MongoClient is route in to MongoDB, from this we'll get database and collections to work with (more on this later). Instance of MongoClient (e.g. mongoClient above) will ordinarily be a singleton in our application. However, if we need to connect via different credentials (different user names and passwords) we want a MongoClient per set of credentials.

It is important to limit the number of MongoClient instances in our application, hence why we suggest a singleton - the MongoClient is effectively the connection pool, so for every new MongoClient, we are opening a new pool. Using a single MongoClient (and optionally configuring its settings) will allow the driver to correctly manage connections to the server. This MongoClient singleton is safe to be used by multiple threads.

One final thing we need to be aware of: you want your application to shut down the connections to MongoDB when it finishes running. Always make sure your application or web server calls MongoClient.close() when it shuts down.

MongoDB doesn't have tables, rows, columns, joins etc. There are some new concepts of a database, the documents are stored in collections, rather than your database being made up of tables of data

MongoDB(NoSQL) vs Database(SQL)

  • document--data/records/rows
  • collection--table
  • database---database

Selecting Databases and Collections

Creating and getting a database or collection is extremely easy in MongoDB:

DB database = mongoClient.getDB("TheDatabaseName");

We can replace "TheDatabaseName" with whatever the name of your database is. If the database doesn't already exist, it will be created automatically the first time you insert anything into it, so there's no need for null checks or exception handling on the off-chance the database doesn't exist.

Getting the collection you want from the database is simple too:

DBCollection collection = database.getCollection("TheCollectionName");

Inserting Collection in MongoDB from Java

Prerequisites
  • Make sure you started the MongoDB server using mongod command
  • Verify pom entry for MongoDB driver in pom.xml

MongoDB server startup

Just above two steps are enough. Here the main class to save document in MongoDB

package in.javavillage.mongodb;

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoDBWithJava {
	public static void main(String[] args) {

		List<String> qualification = Arrays.asList("M.Sc", "M.Tech");
		DBObject employee = new BasicDBObject("empId", "JV54601")
                .append("name", "Soha SK")
                .append("address", new BasicDBObject("street", "Gandhi Nagar")
                                             .append("city", "Chennai")
                                             .append("state", "TN")
                                             .append("zip", 12345))
                .append("qualification", qualification);

		MongoClient mongoClient = null;
		try {
			mongoClient = new MongoClient();
			DB database = mongoClient.getDB("Examples");
			DBCollection collection = database.getCollection("people");
			    
			collection.insert(employee);
			
			mongoClient.close();
			
			System.out.println("completed");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}


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>in.javavillage</groupId>
	<artifactId>MongoDbWithJava</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>MongoDB with Java</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<skip.tests>false</skip.tests>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.12.3</version>
		</dependency>

	</dependencies>
</project>
Project Structure

MongoDB Project Structure

After executing above class just verify MongoDB by using mongo command for records.

MongoDB Results