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!

Introduction to JetBrains IntelliJ IDEA Community Edition

In this post I will introduce to you the JetBrains IntelliJ IDEA, one the the most powerful IDE (Integrated Development Environment) for Java development or other languages that run on the JVM such as Groovy and Scala. IntelliJ IDEA comes in two editions, the IntelliJ IDEA Ultimate Edition and the IntelliJ IDEA Community Edition.

The IntelliJ IDEA Community Edition is an open source version of Intelli JDEA. That’s mean you can use it for free. If you works with standard Java, Groovy, Scala or mobile development using Android then the Community Edition can be your choice. If you works with in web or Java EE development then the Ultimate Edition is the way to go.

Here are some features that you will get when using the IntelliJ IDEA Community Edition:

  • An Intelligent code editor that has all the smarts for understanding Java, XML and Groovy code
  • Refactorings, code inspections and intentions, super-fast navigation and search
  • Testing frameworks integration: JUnit and TestNG
  • Build tools support: Ant and Maven
  • Popular version control systems integration: CVS, Subversion and Git
  • Swing UI designer

After a bit of introduction, let’s begin the installation.

Step 1. Getting the Installation Distribution

  • Download the installation package of the IntelliJ IDEA Community Edition.
  • Click this link to go the the download page.
  • On the page you can see two editions, select the Community Edition. The current version available when this post was written is the version 12.1.4. You can also see that the download are available for Windows, Mac OS X and Linux. For this post I will download the Windows version. The download size for the Windows installer is around 130MB.

Step 2. Install IntelliJ IDEA Community Edition

  • To begin, double click the installer you’ve download, for example ideaIC-12.1.4.exe.
  • You’ll be greeted with the following screen

    intellij-idea-community-edition-setup-step-1

    IntelliJ IDEA Setup Welcome Screen

  • Prest the Next button to continue.
  • You’ll be ask the installation location. On Windows it will be default to the C:Program Files directory
  • Press Next for a couple of times until the installation complete.
  • When you choose to run the IntelliJ IDEA for the first time you’ll get the following screen

    Installation Complete Screen

    Installation Complete Screen

  • Press OK button to start IntelliJ IDEA for the first time. You will be shown a splash screen right after you press the button and continued by the screen welcoming you to the IDE.

    Welcome to IntelliJ IDEA

    Welcome to IntelliJ IDEA

Step 3. Now you have the InteliJ IDEA Community Edition installed in your machine. Let’s create your first program using IDEA.

  • From the Welcome Screen above click the Create New Project menu.
  • New Project dialog window will be shown. In this dialog you can do:

    Create a New Project Window Dialog

    Create a New Project Window Dialog

    1. Enter the Project Type, choose Java Module.
    2. Define the Project Name. We’ll just name it HelloWorld.
    3. Choose the Project Location diretory.
    4. Select the JDK version you’ll be using.
    5. Press the Next button followed by the Finish button to continue.

Step 4. IntelliJ IDEA Main Window, creating HelloWorld.java

  • Here is the Main Window of IntelliJ IDEA.

    IntelliJ IDEA Community Edition

    IntelliJ IDEA Community Edition

  • The bigger screen shot of the project explorer panel.

    Project Explorer Window

    Project Explorer Window

  • Before we create a class let’s create a package.
  • Right click the src folder, continued by selecting the New and Package menu.
  • Enter the package name, for instance org.kodejava.introduction
  • To create a class right click on the newly created package, select New and Java Class menu.
  • In the Create New Class dialog enter HelloWorld in the Name text field and choose Class from the Kind drop down selection.
  • Type the following code in the editor.
    package org.kodejava.introduction;
    
    public class HelloWorld {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public static void main(String[] args) {
            HelloWorld hello = new HelloWorld();
    
            String name = "world";
            hello.setName(name);
            hello.sayHello();
        }
    
        private void sayHello() {
            System.out.println("Hello " + getName() + "!");
        }
    
    }
  • Press Shift + F10 or click the green Run button to execute your code.
  • And we are done!

Other things you can do next is to learn more about the menu and the keyboard shortcuts that you can use while working with the IDE. One good place is to look at the HelpTip of the Day menu. You might also want to read the following cheat sheet from the DZone Refcardz, IntelliJ IDEA Cheat Sheet.

That’s finishes our introduction to the IntelliJ IDEA Community Edition IDE. I hope you can continue your learning and this IDE will surely help you to understand Java better. Because it is not just a tool to write code, it will give you a lot of suggestion so that you can always improve your code quality.