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.