Using Dockerised Mongodb in a Java Application

In this article we will look at how to set up MongoDB in a docker, and connect to it from a local Java application.

Setting up MongoDB in Docker

A guide for setting up Docker can be found here.

We will download a ready made instance of mongo db from the Docker store. The link to the mongo docker is:

To install it:

docker pull mongo


make a directory for mongo to write data to on our host pc (or mac in this case):

mkdir -p ~/mongo-data 

Run mongo and mount the above directory within the container as /data/db:

docker run --name da-mongo -v ~/mongo-data:/data/db -d mongo

You should see output similar to the following:


The –name flag means that our mongodb instance can be retrieved by the name da-mongo. After restarting docker, you can start this instance via the name:

docker start da-mongo

And if you run docker ps you can ensure that the mongo database is running:


If you switch back to the mongo-data directory that we created, you will see that it has now been populated from mongo db:


We have mongodb up and running in a container!

You can connect to our da-mongo instance via docker mongo as follows:

 docker run -it --link da-mongo:mongo --rm mongo sh -c 'exec mongo "$MONGO_PORT_27017_TCP_ADDR:$MONGO_PORT_27017_TCP_PORT/test"'

This command will open mongo in docker and connect to (or create if it does not exist) the test database:


Bonus: Mongo Express in Docker

Mongo Express is a web based UI for mongo. You can of course install it locally, but happily it exists in a docker image too.

To install it:

docker-pull mongo-express

To run it, we docker run our mongo-express container and link it to our mongo instance, in this case named as da-mongo:

 docker run --link da-mongo:mongo -p 8081:8081 mongo-express


Once that is done, in your navigator you can connect to Mongo Express on localhost:8081:


From within Mongo Express you view and edit the content of the databases and run queries as required without having to resort to the command line.

Setting up the Java Application

We will in this article develop a local Java Application to communicate to the Dockerised Mongodb. We could also choose to build our Java Application inside a Docker Container too, but won’t in this article. For details on how to develop inside a Docker container, look here.

First off, create a new Maven application. With Maven we can easily download the necessary mongodb driver. In these steps I am using NetBeans


Name our application MongoClientTest


With a Maven application, to download the mongo driver we need to access the pom.xml file in the Project Files folder of our project:


Inside, we will insert the following XML snippet to define our dependency.


  <!-- -->

(Ensure that you have the correct version for your installed mongodb)

Now, we need to add a Java Class in which we will code our application.

  1. In the projects view, right click on Source Packages add choose New -> Java Class…
  2. Add a class called


To get the application started and test that Maven downloads the correct dependencies, just add a Hello World main method in the file:


Then, run the application. It will ask to select the main from a class, select MongoTest, and then Maven will download your dependencies … notably, mongo-java-driver:


Now that we have a Mongo database happily running in Docker, and a java application that builds with driver to talk to it, we need to get the two parts talking…

Connecting to MongoDB

To connect to MongoDB use MongoClient as follows;

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

So, for example, we can create a ConnectDB() method, and call it:

public class MongoTest {
 * @param args the command line arguments
 public static void main(String[] args) {
 System.out.print("Hello Everybody! ");

 public static void ConnectDB() {
 MongoClient mongoClient = new MongoClient("localhost", 27017); 


Hello Everybody! May 31, 2017 8:13:24 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

Listing Databases:

To list databases use the getDatabaseNames() method of mongoClient


or else iterate on a MongoCursor

 MongoCursor dbsCursor = _mongoClient.listDatabaseNames().iterator();
 while(dbsCursor.hasNext()) {

Retrieving a Collection

Collections are like tables in a standard DB. Each database can have multiple collections.

To retrieve a specific Collection from our Database:

DB db = mongo.getDB("test");
DBCollection table = db.getCollection("myCollection");

What is interesting here is that if the collection doesn’t exist, Mongo will automatically create it for you.

And to list all collections we can use the following code;

Set<String> collections = db.getCollectionNames();

CRUD Operations

One way of inserting documents into Mongo is using the BasicDBObject class. By using this, we can create documents and then insert them into a collection, for example:

DBCollection myCol = db.getCollection("myCollection");
BasicDBObject document = new BasicDBObject();
document.put("videoname", "Blade Runner");
document.put("Actor", "Harrison Ford");
document.put("Actor2", ""); document.put("Released", "1982"); document.put("createdDate", new Date()); myCol.insert(document);

To find and read a document, we can query the collection and use a cursor:

DBCollection myCol = db.getCollection("myCollection");

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("videoname", "Blade Runner");

DBCursor cursor = myCol.find(searchQuery);

while (cursor.hasNext()) {

To update a value, we can do the following:

DBCollection myCol = db.getCollection("myCollection");

BasicDBObject newDocument = new BasicDBObject(); newDocument.put("Actor2", "Rutger Hauer"); BasicDBObject searchQuery = new BasicDBObject().append("videoname", "Blade Runner"); myCol.update(searchQuery, newDocument);

to delete a value, we remove it from the collection:

BasicDBObject document = new BasicDBObject();
document.put("videoname", "Blade Runner");

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s