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 convert Map into JSON?

This example show you how to convert a java.util.Map into JSON string and back to Map again.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        // Convert a Map into JSON string.
        Gson gson = new Gson();
        String json = gson.toJson(colours);
        System.out.println("json = " + json);

        // Convert JSON string back to Map.
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
    }
}

Here is the result of the program:

json = {"RED":"#FF0000","WHITE":"#FFFFFF","BLUE":"#0000FF","BLACK":"#000000","YELLOW":"#FFFF00","GREEN":"#008000"}
map.get = #FF0000
map.get = #FFFFFF
map.get = #0000FF
map.get = #000000
map.get = #FFFF00
map.get = #008000

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I convert collections into JSON?

This example show you how to convert Java collections object into JSON string. For Student class use in this example you can find it the previous example on How do I convert object into JSON?.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CollectionToJson {
    public static void main(String[] args) {
        //
        // Converts a collection of string object into JSON string.
        //
        List<String> names = new ArrayList<String>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);

        //
        // Converts a collection Student object into JSON string
        //
        Student a = new Student("Alice", "Apple St", getDOB(2000, 10, 1));
        Student b = new Student("Bob", "Banana St", null);
        Student c = new Student("Carol", "Grape St", getDOB(2000, 5, 21));
        Student d = new Student("Mallory", "Mango St", null);

        List<Student> students = new ArrayList<Student>();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);

        //
        // Converts JSON string into a collection of Student object.
        //
        Type type = new TypeToken<List<Student>>() {
        }.getType();
        List<Student> studentList = gson.fromJson(jsonStudents, type);

        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
        }
    }

    private static Date getDOB(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
}

Here is the result of our program:

jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I convert array into JSON?

In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // Create a new instance of Gson
        Gson gson = new Gson();

        // Convert numbers array into JSON string.
        String numbersJson = gson.toJson(numbers);

        // Convert strings array into JSON string
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        // Convert from JSON string to a primitive array of int.
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int number : fibonacci) {
            System.out.print(number + " ");
        }
        System.out.println("");

        // Convert from JSON string to a string array.
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (String weekDay : weekDays) {
            System.out.print(weekDay + " ");
        }
        System.out.println("");

        // Converting multidimensional array into JSON
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        // Convert JSON string into multidimensional array of int.
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int[] i : dataMap) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    }
}

Here is our code result:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5 
4 5 6

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How does Gson handles object fields?

In this example you’ll see how the Gson library handles the object fields. For object fields to be serialized into JSON string it doesn’t need to use any annotations, it can even read private fields. If you have a null value field it will not be serialized into JSON string. To exclude a field from serialization you can mark the field with the transient keyword.

In the snippet below we create a People object. This object has a null value field named age, this will not included in the serialization because we didn’t assign any value to it. The secret field is also not serialized because we mark it with transient keyword.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

import java.util.Calendar;

public class GsonFieldExample {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(1980, Calendar.NOVEMBER, 11);
        People people = new People("John", "350 Banana St.", dob.getTime());
        people.setSecret("This is a secret!");

        Gson gson = new Gson();
        String json = gson.toJson(people);
        System.out.println("json = " + json);
    }
}

If your run the code above you’ll see the following line printed:

json = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}

Here is the People class.

package org.kodejava.example.google.gson;

import java.util.Date;

public class People {
    private String name;
    private String address;
    private Date dateOfBirth;
    private Integer age;
    private transient String secret;

    public People(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I convert JSON into object?

On the previous example, How do I convert object into JSON? we convert object into JSON string. In this example you will see how to do the opposite, converting JSON string back into object.

To convert JSON string to object use Gson.fromJson() method. This method takes the JSON string and the object type of the JSON string to be converted.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

public class JSONToStudent {
    public static void main(String[] args) {
        String json = "{" +
                "'name' : 'Duke'," +
                "'address' : 'Menlo Park'," +
                "'dateOfBirth' : 'Feb 1, 2000 12:00:00 AM'" +
                "}";

        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);

        System.out.println("s.getName()        = " + student.getName());
        System.out.println("s.getAddress()     = " + student.getAddress());
        System.out.println("s.getDateOfBirth() = " + student.getDateOfBirth());
    }
}

This example will print the following result:

s.getName()        = Duke
s.getAddress()     = Menlo Park
s.getDateOfBirth() = Tue Feb 01 00:00:00 WITA 2000

You can find the Student class on the previous example, How do I convert object into JSON?.

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>

How do I convert object into JSON?

In this example we are using Google Gson to convert an object (Student object) into JSON notation. Practically we can use this library to convert any object in Java and it is quite simple. You just need to create an instance of Gson class and then call the .toJson() method and pass the object to be converted into JSON string.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

import java.util.Calendar;

public class StudentToJson {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(2000, 1, 1, 0, 0, 0);
        Student student = new Student("Duke", "Menlo Park", dob.getTime());

        Gson gson = new Gson();
        String json = gson.toJson(student);
        System.out.println("json = " + json);
    }
}

When you run the example above you’ll get an output like:

json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}

Below is our Student class.

package org.kodejava.example.google.gson;

import java.io.Serializable;
import java.util.Date;

public class Student implements Serializable {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}

Maven Dependencies


<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>