How do I insert a document into MongoDB collection?

In the last MongoDB example, How documents are represented in MongoDB Java Driver?, we’ve seen how MongoDB JSON documents are represented in MongoDB Java driver.

Using this knowledge it is time for us to learn how to insert documents into MongoDB collections. We will create a code snippet that will insert documents into the teachers collections in the school database. We will see the complete code snippet first followed by a detail description of the code snippet. So, let’s begin with the code snippet.

package org.kodejava.example.mongodb;

import com.mongodb.*;

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

public class MongoDBInsertDocument {
    public static void main(String[] args) throws UnknownHostException {
        // Creates MongoDB client instance.
        MongoClient client = new MongoClient(
                new ServerAddress("localhost", 27017));

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

        // Gets the teachers collection from the database.
        DBCollection collection = database.getCollection("teachers");
        collection.drop();

        // Creates a document to be stored in the teachers collections.
        DBObject document = new BasicDBObject("firstName", "John")
                .append("lastName", "Doe")
                .append("subject", "Computer Science")
                .append("languages", Arrays.asList("Java", "C", "C++"))
                .append("email", "[email protected]")
                .append("address",
                        new BasicDBObject("street", "Main Apple St. 12")
                                .append("city", "New York")
                                .append("country", "USA"));

        // Prints the value of the document.
        System.out.println("document = " + document);

        // Inserts the document into the collection in the database.
        collection.insert(document);

        // Prints the value of the document after inserted in the collection.
        System.out.println("document = " + document);
    }
}

The snippet should be easy to understand. But I will explain about it a little bit more down here. In the beginning of the code snippet we begin with the following lines:

public static void main(String[] args) throws UnknownHostException {           
    // Creates MongoDB client instance.
    MongoClient client = new MongoClient(
        new ServerAddress("localhost", 27017));
}

This is how we bootstrap / start the MongoDB Java Driver. It connects to MongoDB server at localhost port 27017. If you omit using this ServerAddress class it will also connect to localhost port 27017 as the default. We also need to add the throws UnknownHostException to the main method signature because creating a MongoClient might throw this exception when the server is not available. Or you could wrapped the code inside a try-catch block instead. On the next lines you can see the following codes.

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

// Gets the teachers collection from the database.
DBCollection collection = database.getCollection("teachers");
collection.drop();

This code snippet tells you how to get the database, the school database. We get the database using the client.getDB() method call and passing the database name as the argument. The reference to this database then stored in a variable called database. After having the database we can then access the teachers collections by calling the database.getCollection() method.

You also notice that we call collection.drop(), which will clear the collection. We use this for our example purpose only, just to make sure that every time we execute our code snippet the collection will be cleaned before we insert some document.

Next, we creates the document to be stored in the teachers collections. We define a variable called document with DBObject type which refer the an instance of BasicDBObject type. And we add some fields in the document, and array type field and another embedded document.

// Creates a document to be stored in the teachers collections.
DBObject document = new BasicDBObject("firstName", "John")
        .append("lastName", "Doe")
        .append("subject", "Computer Science")
        .append("languages", Arrays.asList("Java", "C", "C++"))
        .append("email", "[email protected]")
        .append("address",
                new BasicDBObject("street", "Main Apple St. 12")
                        .append("city", "New York")
                        .append("country", "USA"));

In the last three lines we do the following:

// Prints the value of the document.
System.out.println("document = " + document);

// Inserts the document into the collection in the database.
collection.insert(document);

// Prints the value of the document after inserted in the collection.
System.out.println("document = " + document);

In the first print out we will see the document as defined in the previous lines using the BasicDBObject with all the defined field values. Then it followed by calling the collection.insert() method which will insert the document into the collections.

In the last line we print out the document once again. You might see that the result is almost the same as the first print out, but you will notice that after inserted into the collection the document now have another field, which is the _id field assigned by the Java Driver as the object id of the document. The _id is added automatically if we didn’t define the _id field in the document. It is essentially the same as if we define the document using the following code, where _id it a type of org.bson.types.ObjectId.

DBObject document = new BasicDBObject("_id", new ObjectId());

And these are the actual output of the code above:

document = { 
    "firstName" : "John" , 
    "lastName" : "Doe" , 
    "subject" : "Computer Science" , 
    "languages" : [ "Java" , "C" , "C++"] , 
    "email" : "[email protected]" , 
    "address" : { 
        "street" : "Main Apple St. 12" , 
        "city" : "New York" , 
        "country" : "USA"
    }
}

document = { 
    "firstName" : "John" , 
    "lastName" : "Doe" , 
    "subject" : "Computer Science" , 
    "languages" : [ "Java" , "C" , "C++"] , 
    "email" : "[email protected]" , 
    "address" : { 
        "street" : "Main Apple St. 12" , 
        "city" : "New York" , 
        "country" : "USA"
    },
    "_id" : { "$oid" : "5408744803649d9155a296b7" }
}

How documents are represented in MongoDB Java Driver?

MongoDB documents are stored inside a collections as a JSON (JavaScript Object Notation) document. It’s a string of key-value pairs data. JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

When we are working in the MongoDB shell we can type in this document as a string that follow JSON data format. But how do we create this JSON document when working within a Java programming. This blog post will show you how to represent a document using Java Driver for MongoDB.

If you recall a key-value pairs data type you will remember that Java have a java.util.Map that can represent data structure in this format. So you might think that you can use a generic type of Map<String, Object> to store this data. But, because in MongoDB’s document the order of keys in a document is quite important to make sure the operations such as find, insert, update and remove work correctly, using a Map to represent a document can be quite dangerous.

MongoDB has a special interface called as com.mongodb.DBObject and its implementation class in com.mongodb.BasicDBObject that can be use to create or represent a document in MongoDB database. The DBObject is actually a map like structure with a key-value pairs. If you look up to the class hierarchy you can actually see that a BasicDBObject is inherited from the java.util.LinkedHashMap class.

The code snippet below will show you how to create a BasicDBObject to represent a MongoDB document.

package org.kodejava.example.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import java.util.Arrays;

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

        // Creates an empty document.
        DBObject emptyDoc = new BasicDBObject();
        System.out.println("emptyDoc = " + emptyDoc);

        // Creates a simple document with a given key and value.
        DBObject simpleDoc = new BasicDBObject("name", "John Doe");
        System.out.println("simpleDoc = " + simpleDoc);

        // Creates a document with embedded document and arrays.
        DBObject document = new BasicDBObject("firstName", "Foo")
                .append("lastName", "Bar")
                .append("age", 25)
                .append("email", "[email protected]")
                .append("address",
                        new BasicDBObject("street", "Sunset Boulevard 123")
                                .append("city", "New York")
                                .append("country", "USA"))
                .append("hobbies", Arrays.asList("Swimming", "Cycling", "Running"));
        System.out.println("document = " + document);
    }
}

In the code above we have create three documents as an example. The first one is an empty document which created by instantiating a BasicDBObject class with no arguments specified. The second one we create a document with a single key and value. This key and value is passed as an argument when we create the BasicDBObject.

The last example show you how to create a document with multiple keys, embedded document and an arrays. To add more fields to the BasicDBObject we can call a chain of the append() method with a specified key and value. The key will be a string and the value is a type of java.lang.Object.

An embedded document is created simply by instantiating another BasicDBObject and assign it as a value of a document key. In the example above the address field is an embedded document inside the document. Which contains another fields such as street, city and country.

If you want to see how the JSON string of this document is look like you can run the code above. You will see something like the output below as the result.

emptyDoc = { }

simpleDoc = { "name" : "John Doe" }

document = { 
    "firstName" : "Foo" , 
    "lastName" : "Bar" , 
    "age" : 25 , 
    "email" : "[email protected]" , 
    "address" : { 
        "street" : "Sunset Boulevard 123" , 
        "city" : "New York"
    } , 
    "hobbies" : [ "Swimming" , "Cycling" , "Running"]
}

That’s the basic that you need to know on how to create a document using MongoDB Java Driver. You will use this document when doing some database operation in MongoDB such as finding a document, inserting, updating and removing document from collection in the database.

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!

Installing and Running MongoDB in Windows 7

What is MongoDB

In this post you will see how to install and running MongoDB database server on Windows 7. What is MongoDB? MongoDB is a NoSQL database. MongoDB is a non-relational JSON document store, a document oriented database. Non-relational means that it doesn’t support the relational algebra that most often expressed in SQL like what RDBMS such as Oracle or MySQL does. The document here is not a Microsoft Word documents or such, but it is a JSON (JavaScript Object Notation) documents.

And if you don’t know what it is look like, here are some examples of JSON documents:

{"firstName" : "John", "lastName" : "Doe", "cityOfBirth" : "New York"}
{"firstName" : "Julia", "lastName" : "Roberts", "movieTitles" : ["Pretty Woman", "Nothing Hill", "Runaway Bride"]}

Other characteristics of MongoDB are: it has a dynamic schema, it doesn’t support SQL language, it doesn’t support Joins, and it doesn’t support transactional across multiple collections.

 

MongoDB Installation

After you know a bit of MongoDB lets get started with the installation process. Here are the step by step of the MongoDB installation.

  • Downloads Windows 64-bit MongoDB installer at //www.mongodb.org/downloads. When this post is written the binary file name for Windows 64-bit is mongodb-win32-x86_64-2008plus-2.6.3-signed.msi.
  • After you have finish the download the installer double click the file to start the installation wizard.

    Welcome to MongoDB Setup

    Welcome to MongoDB Setup

  • Press the Next button for the next screen and check I accept the terms in the License Agreement check box and press the Next button to continue.

    End-User License Agreement

    End-User License Agreement

  • The next step is to choose the setup type. There are three types of setup available, Typical, Custom and Complete. For now we will choose Complete. So click the Complete button to continued the installation process.

    Choose Setup Type

    Choose Setup Type

  • Press the Install button to begin installation process.

    Ready To Install MongoDB

    Ready To Install MongoDB

  • After pressing the Install button you can see the screen of MongoDB installation process. Wait until the installation is done.

    Installing MongoDB

    Installing MongoDB

  • And finally you have the MongoDB database installed. Click the Finish button to end the installation process.

    Completed MongoDB Installation

    Completed MongoDB Installation

The steps above have finalize your MongoDB installation. If you check in your C:\Program Files directory you will see the MongoDB installation directory in there. There will be a bin directory under C:\Program Files\MongoDB 2.6 Standard where all the MongoDB application files. Now you have install the database server lets run and check the database server.

 

Running MongoDB

For this step we will focus on two files from the bin directory of the MongoDB installation. The mongod.exe and mongo.exe. The first executable is the MongoDB database engine daemon while the second executable is the shell program to access the MongoDB.

To run the database do the following steps:

  • Create data directory. By default MongoDB look for \data\db directory in the root Drive from where you run the mongod. For example you can create C:\data\db. Or you can use the --dbpath argument to tell MongoDB where to store the data.
  • Open Command Prompt and cd to C:\Program Files\MongoDB 2.6 Standard\bin and type mongod to start the daemon.
    MongoDB mongod

    MongoDB mongod

    The screen above shows you that the MongoDB is successfully started, using the dbpath \data\db and it ready and listening for connections on the default port 27017.

 

Running The Shell

  • Open Command Prompt and cd to C:\Program Files\MongoDB 2.6 Standard\bin.
  • Run mongo.exe to start the shell. You’ll see a welcome message to the MongoDB shell.

    MongoDB mongo shell

    MongoDB mongo shell

  • In the shell above we run a couple of commands:
  • use peopledb command ask the MongoDB to change to the persons collections, if it doesn’t exist Mongo will create one.
  • To add document to the collections we can call db.persons.insert(); and passing the JSON document as the arguments.
  • To query the collection we can use db.persons.find().
  • If you want for instance to find Julia in the collection you can do db.persons.find({"firstName" : "Julia"})
  • To close the shell we can call quit() command.

That’s all for now, I hope this post is useful for you. In the next post I will show you how to create a simple Java application that use Mongo Java Driver to store data using Java programming into the MongoDB database. So, see you in the next post. Thank you.