Book Image

MongoDB Cookbook

By : Amol Nayak
Book Image

MongoDB Cookbook

By: Amol Nayak

Overview of this book

<p>MongoDB is a high-performance and feature-rich NoSQL database that forms the backbone of numerous complex development systems. You will certainly find the MongoDB solution you are searching for in this book.</p> <p>Starting with how to initialize the server in three different modes with various configurations, you will then learn a variety of skills including the basics of advanced query operations and features in MongoDB and monitoring and backup using MMS. From there, you can delve into recipes on cloud deployment, integration with Hadoop, and improving developer productivity. By the end of this book, you will have a clear idea about how to design, develop, and deploy MongoDB.</p>
Table of Contents (17 chapters)
MongoDB Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Connecting to a single node from a Java client


This recipe is about setting up the Java client for MongoDB. You will be repeatedly referring to this recipe while working on others, so read it very carefully.

Getting ready

The following are the prerequisites for this recipe:

  • Version 1.6 or above of Java SDK is recommended.

  • Use the latest available version of Maven. Version 3.1.1 was the latest at the time of writing this book.

  • Use the MongoDB Java driver. Version 2.11.3 was the latest at the time of writing this book.

  • Connectivity to the Internet to access the online Maven repository or a local repository is needed. Alternatively, you might choose an appropriate local repository accessible to you from your computer.

  • The Mongo server is up and running on the localhost and on port 27017. Take a look at the first recipe, Single node installation of MongoDB, and start the server.

How to do it…

Let's take a look at the steps in detail:

  1. Install the latest version of JDK if you don't already have it on your machine. We will not be going through the steps to install JDK in this recipe but, before moving on with, next step, the JDK should be present. Type javac -version on the shell to check for the version installed.

  2. Once the JDK is set up, the next step is to set up Maven. Skip the next three steps if Maven is already installed on your machine.

  3. Maven needs to be downloaded from http://maven.apache.org/download.cgi. Choose the binaries in the .tar.gz or .zip format and download it. This recipe is executed on a machine that runs on the Windows platform; thus, these steps are for installation on Windows. The following screenshot shows the download page of Maven:

  4. Once the archive is downloaded, we need to extract it and put the absolute path of the bin folder in the extracted archive in the operating system's path variable. Maven also needs the path of the JDK to be set as the JAVA_HOME environment variable. Remember to set the root of your JDK as the value of this variable.

  5. All we need to do now is type mvn -version in the command prompt. If you see the version of Maven on the command prompt, we have successfully set up Maven:

    > mvn -version
    
  6. At this stage, we have Maven installed, and we are now ready to create our simple project to write our first Mongo client in Java. We will start by creating a project folder. Let's assume that we create a folder called Mongo Java. Then, we will create a folder structure src/main/java in this project folder. The root of the project folder then contains a file called pom.xml. Once this folder creation is done, the folder structure should look as follows:

          Mongo Java      
          +--src  
          |     +main
          |         +java
          |--pom.xml
    
    
  7. We just have the project skeleton with us now. We will now add some content to the pom.xml file. Not much is needed for this. Add the following code snippet in the pom.xml file and save it:

    <project>
        <modelVersion>4.0.0</modelVersion>
        <name>Mongo Java</name>
        <groupId>com.packtpub</groupId>
        <artifactId>mongo-cookbook-java</artifactId>
        <version>1.0</version>
        <packaging>jar</packaging>
        <dependencies>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>2.11.3</version>
            </dependency>
        </dependencies>
    </project>
  8. Finally, we will write our Java client that will be used to connect to the Mongo server and execute some very basic operations. The following is the Java class located at src/main/java in the com.packtpub.mongo.cookbook package, and the name of the class is FirstMongoClient:

    package com.packtpub.mongo.cookbook;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBObject;
    import com.mongodb.MongoClient;
    
    import java.net.UnknownHostException;
    import java.util.List;
    
    /**
     * Simple Mongo Java client
     *
     */
    public class FirstMongoClient {
    
        /**
         * Main method for the First Mongo Client. Here we shall be connecting to a mongo
         * instance running on localhost and port 27017.
         *
         * @param args
         */
        public static final void main(String[] args) 
    throws UnknownHostException {
            MongoClient client = new MongoClient("localhost", 27017);
            DB testDB = client.getDB("test");
            System.out.println("Dropping person collection in test database");
            DBCollection collection = testDB.getCollection("person");
            collection.drop();
            System.out.println("Adding a person document in the person collection of test database");
            DBObject person = 
    new BasicDBObject("name", "Fred").append("age", 30);
            collection.insert(person);
            System.out.println("Now finding a person using findOne");
            person = collection.findOne();
            if(person != null) {
                System.out.printf("Person found, name is %s and age is %d\n", person.get("name"), person.get("age"));
            }
            List<String> databases = client.getDatabaseNames();
            System.out.println("Database names are");
            int i = 1;
            for(String database : databases) {
                System.out.println(i++ + ": " + database);
            }
      System.out.println("Closing client");
            client.close();
        }
    }
  9. It's now time to execute the preceding Java code. We will execute it using Maven from the shell. You should be in the same directory as the pom.xml file of the project:

    mvn compile exec:java -Dexec.mainClass=com.packtpub.mongo.cookbook.FirstMongoClient
    

How it works…

Those were quite a lot of steps to follow! Let's look at some of them in more detail. Everything up to step 6 is straightforward and doesn't need any explanation. Let's look at the other steps.

The pom.xml file we have here is pretty simple. We defined a dependency on Mongo's Java driver. It relies on the online repository (http://search.maven.org) for resolving the artifacts. For a local repository, all we need to do is define the repositories and pluginRepositories tags in pom.xml. For more information on Maven, refer to the Maven documentation at http://maven.apache.org/guides/index.html.

Now, for the Java class, the org.mongodb.MongoClient class is the backbone. We will first instantiate it using one of its overloaded constructors that gives the server's host and port. In this case, the hostname and port were not really needed as the values provided are the default values anyway, and the no-argument constructor would have worked well too. The following line of code instantiates this client:

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

The next step is to get the database; in this case, test using the getDB method. This is returned as an object of type com.mongodb.DB. Note that this database might not exist, yet getDB will not throw any exception. Instead, the database will get created whenever we add a new document to the collection in this database. Similarly, getCollection on the DB object will return an object of type com.mongodb.DBCollection, representing the collection in the database. This too might not exist in the database and will get created automatically upon the insertion of the first document.

The following lines of code from our class show how to get an instance of DB and DBCollection:

DB testDB = client.getDB("test");
DBCollection collection = testDB.getCollection("person");

Before we insert a document, we will drop the collection so that even upon multiple executions of the program, we will have just one document in the person collection. The collection is dropped using the drop() method on the DBCollection object's instance. Next, we will create an instance of com.mongodb.DBObject. This is an object that represents the document to be inserted in the collection. The concrete class used here is BasicDBObject, which is a type of java.util.LinkedHashMap class, where the key is a string and the value is an object. The value can be another DBObject, too, in which case it is a document nested within another document. In our case, we have two keys: name and age. These are the field names in the document to be inserted, and the values are of type string and integer, respectively. The append method of BasicDBObject adds a new key-value pair to the BasicDBObject instance and returns the same instance, which allows us to chain the append method calls to add multiple key value pairs. DBObject is then inserted into the collection using the insert method. This is how we instantiated a DBObject for the person and inserted it in the collection:

DBObject person = new BasicDBObject("name", "Fred").append("age", 30);
collection.insert(person);

The findOne method on DBCollection is straightforward and returns one document from the collection. This version of findOne doesn't accept DBObject (which, otherwise, acts as a query executed before a document is selected and returned) as a parameter. This is synonymous to executing a db.person.findOne() from the Mongo shell.

Finally, we will simply invoke getDatabaseNames to get a list of databases names in the server. At this point of time, we should at least be having the test and local databases in the returned result. Once all the operations are completed, we will close the client. The MongoClient class is thread-safe; generally, one instance is used per application. To execute the program, we will use Maven's exec plugin. On executing step 9, we will see the following output on the console:

[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ mongo-cookbook-java ---
Dropping person collection in test database
Adding a person document in the person collection of test database
Now finding a person using findOne
Person found, name is Fred and age is 30
Database names are
1: local
2: test
Closing client
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.183s
[INFO] Finished at: Wed Oct 30 00:42:29 IST 2013
[INFO] Final Memory: 7M/19M
[INFO] ------------------------------------------------------------------------