How do I connect to a MongoDB Database?

In the previous post you have seen how we installed the MongoDB database server and try to use the MongoDB shell to manipulate collections in the database. You also have been introduced how to obtain and setup the MongoDB Java Driver that we can use to manipulate the MongoDB database from a Java program.

Starting from this post we will begin to explore more on how to use the power of MongoDB Java Driver to work with MongoDB. You will see how we are connect to the database, how to do a CRUD operation (Create, Read, Update and Delete) with Java Driver. But first let see how we create a connection to a database in MongoDB.

Here is our first code snippet, it shows you how to bootstrap the MongoDB to open a connection to a database.

package org.kodejava.example.mongodb;

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Random;

public class MongoDBConnect {
    public static void main(String[] args) {
        try {
            MongoClient client =
                    new MongoClient(new ServerAddress("localhost", 27017));

            DB database = client.getDB("school");
            DBCollection students = database.getCollection("students");
            students.remove(new BasicDBObject());

            String[] types = {"Homework", "Quiz", "Essay"};
            for (int i = 1; i <= 10; i++) {
                for (int j = 0; j < 3; j++) {
                    students.insert(new BasicDBObject("student_id", i)
                            .append("type", types[j])
                            .append("score", new Random().nextInt(100)));
                }
            }

            try (DBCursor cursor = students.find()) {
                while (cursor.hasNext()) {
                    System.out.println(cursor.next());
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

What you can see from the code above is. First we bootstrap the MongoDB by create an instance of MongoClient. Here we pass a ServerAddress to define the address of our MongoDB database with information about the host name and the port number. If you just create an instance of MongoClient without any arguments it will use the default address such as localhost for the host and 27017 as the default port number. Creating an instance of MongoClient can produce an UnknownHostException, so we need to place it inside a try-catch statement.

try {
    MongoClient client =
            new MongoClient(new ServerAddress("localhost", 27017));
} catch (UnknownHostException e) {
    e.printStackTrace();
}

After initialize the MongoClient we can connect to a database by calling the getDB() method and passing the database name as argument. In the example above we connect to the school database, the database in MongoDB is represented by the DB class in the com.mongodb package. In the next line after connected to the database you can see that we are getting the students collection from this database. Just for the purpose of this example we then empty the students collection using the remove() method of the DBCollection class.

DB database = client.getDB("school");
DBCollection students = database.getCollection("students");
students.remove(new BasicDBObject());

In the next lines until the end of a code snippet you can see that we populate some random data into the students collections. We call the DBCollection.insert() method to insert documents into the students collection. And finally we read the inserted documents from the students collection using the find() method and iterate the returned cursor one by one until all documents printed on the console. You can also see that we are using the try-with-resource syntax in this code as the DBCursor is already implementing the Java 7 AutoCloseable interface.

String[] types = {"Homework", "Quiz", "Essay"};              
for (int i = 1; i <= 10; i++) {                              
    for (int j = 0; j < 3; j++) {                            
        students.insert(new BasicDBObject("student_id", i)   
                .append("type", types[j])                    
                .append("score", new Random().nextInt(100)));
    }                                                        
}                                                            

try (DBCursor cursor = students.find()) {                    
    while (cursor.hasNext()) {                               
        System.out.println(cursor.next());                   
    }                                                        
}

And here are the sample of the result produced by our code above.

{ "_id" : { "$oid" : "53f47814f524c5037606f2b4"} , "student_id" : 1 , "type" : "Homework" , "score" : 86}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b5"} , "student_id" : 1 , "type" : "Quiz" , "score" : 14}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b6"} , "student_id" : 1 , "type" : "Essay" , "score" : 35}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b7"} , "student_id" : 2 , "type" : "Homework" , "score" : 12}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b8"} , "student_id" : 2 , "type" : "Quiz" , "score" : 96}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b9"} , "student_id" : 2 , "type" : "Essay" , "score" : 51}
{ "_id" : { "$oid" : "53f47814f524c5037606f2ba"} , "student_id" : 3 , "type" : "Homework" , "score" : 54}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bb"} , "student_id" : 3 , "type" : "Quiz" , "score" : 50}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bc"} , "student_id" : 3 , "type" : "Essay" , "score" : 38}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bd"} , "student_id" : 4 , "type" : "Homework" , "score" : 69}

Introduction to MongoDB Java Driver

In the past post Installing and Running MongoDB in Windows 7, you’ve seen how to install and running MongoDB database server. Now we are going to learn how to use the MongoDB Java Driver to access collections from the MongoDB database. To demonstrate this I am going to use Maven and and IntelliJ IDEA. You can use other IDE of your choice of course, such as Eclipse or NetBeans which also support Maven.

Let’s begin by creating our project in IntelliJ IDEA. I am going to use the community edition of IntelliJ IDEA which is free to download. Here are the steps for creating a Maven project in IntelliJ IDEA.

Creating Maven Project

  • Start IntelliJ IDEA. From the Welcome Screen select Create New Project.
  • A New Project wizard will be shown. Select Maven on the Sidebar, check the Create from archetype check box and select maven-archetype-quickstart.

    Maven Project From Archetype

    Maven Project From Archetype

  • Press the Next button to continue.
  • In the next screen you can enter the Maven project information details including the GroupId, ArtifactId, and Version.

    Maven Project Information

    Maven Project Information

  • Press the Next button to continue.
  • In this screen you can override any Maven configuration setting if you want. And you also see the summary of Maven project to be created. We do not modify the setting in this screen.

    Maven Project Summary

    Maven Project Summary

  • Press the Next button to continue.
  • In the final screen we input the Project name and Project location directory.
  • After you input these two information click the Finish button to generate the Maven project in IntelliJ IDEA.

    Maven Project Name and Location

    Maven Project Name and Location

  • Finally you have the Maven project created in IntelliJ IDEA.
  • This is the Maven project structure generated in IntelliJ IDEA.
    Maven Project Structure

    Maven Project Structure

     

Editing the pom.xml File

  • To use the MongoDB Java Driver in our Java application, the first thing we need to is to add the dependency to MongoDB Java Driver in our pom.xml file.
  • Add the following dependency configuration to the pom.xml.
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.12.3</version>
</dependency>
  •  And you’ll have the complete pom.xml file like this configuration below.
<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>org.kodejava.example.mongodb</groupId>
    <artifactId>mongodb-examples</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mongodb-examples</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>mongo-java-driver</artifactId>
            <version>2.12.3</version>
        </dependency>
    </dependencies>
</project>

IntelliJ IDEA will download all the required dependency files from the Maven Central repository if they are not available in you local Maven repository. After configuring the Maven, we are now ready to create a simple program to find a single collection from the MongoDB database.

If you are following the last post about installing and running MongoDB that I have mention in the beginning of this article you know that we have a peopledb and persons collections in our MongoDB database. Now we are going to read it using the MongoDB Java Driver in our Java application. So lets now create the application.

Create Java A Simple MongoDB Client

  • We create our class under the org.kodejava.example.mongodb package. Right click on this package and choose New, Java Class to create a new class.
  • Type in the class name MongoDBHelloWorld, and press OK button.
  • And this is the full code snippet for the MongoDBHelloWorld class.
package org.kodejava.example.mongodb;

import com.mongodb.*;

import java.net.UnknownHostException;

public class MongoDBHelloWorld {
    public static void main(String[] args) {
        try {
            //
            // Creates a new instance of MongoDBClient and connect to localhost
            // port 27017.
            //
            MongoClient client = new MongoClient(
                    new ServerAddress("localhost", 27017));

            //
            // Gets the peopledb from the MongoDB instance.
            //
            DB database = client.getDB("peopledb");

            //
            // Gets the persons collections from the database.
            //
            DBCollection collection = database.getCollection("persons");

            //
            // Gets a single document / object from this collection.
            //
            DBObject document = collection.findOne();

            //
            // Prints out the document.
            //
            System.out.println(document);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
  •  If you run this code you will get the following output printed on the screen.
{ "_id" : { "$oid" : "53e317ae420156bce730d1ff"} , "firstName" : "John" , "lastName" : "Doe" , "cityOfBirth" : "New York"}
  •  This is the JSON document that we’ve store in our peopledb in the MongoDB database.

The Java class above is our first example of how to use the MongoDB Java Driver to access and read a document from the MongoDB database. I hope this example can be a good start for us to learn more about MongoDB. If you have any question just submit it in the comment section below this article. See you on the next post. Thank you!