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 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}