MongoDB tutorial for Java EE developers

This tutorial provides a short introduction to MongoDB no-sql database and shows how to interact with it
from a Java application server (JBoss AS).

MongoDB (which stands for “humongous”) is an open source, high-performance, schema-free, document-oriented database written in the C++ programming language. The database is document-oriented so it manages collections of JSON-like documents.

The easiest (and recommended) way to install MongoDB is to use the pre-built binaries

Download binaries here

Once you’re done, unzip the downloaded binary package to the location of your choice.Then, download the jar driver which is hosted at github.

Download the jar driver here

Copy the file under your JBoss library folder (Ex. C:\jboss-6.0.0.Final\common\lib )

By default MongoDB will store data in \data\db, but it won’t automatically create that folder, so we do so here:

C:\> mkdir \data
C:\> mkdir \data\db

Ok. We’re done with set-up. Now move to the “bin” folder of mongodb

The important binaries for a first run are:

mongod.exe – the database server
mongo.exe – the administrative shell

To start the database, click mongod.exe in Explorer

Data can be inserted directly using the mongo.exe shell or via the Java Mongo db driver.

For this purpose we will create a simple Servlet which will run on JBoss AS 6 and insert some data. The Servlet will insert a Collection containing a DB Object into MongoDB. This is our sample DBObject we’re going to insert:

public class MongoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Mongo m = null;   

    public MongoServlet() {
        // TODO Auto-generated constructor stub
    public void init(ServletConfig config)
        try {
            m = new Mongo( "localhost" );
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
        } catch (MongoException e) {
            // TODO Auto-generated catch block

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        DB db = m.getDB( "test" );

        out.println("Got db");

        BasicDBObject doc = new BasicDBObject();

        doc.put("name", "Michael");
        doc.put("surname", "Owen");
        doc.put("age", 31);

        DBCollection coll = db.createCollection("player", doc);

        BasicDBObject career = new BasicDBObject();

        career.put("goals", 100);
        career.put("matches", 200);

        doc.put("career", career);


        out.println("Inserted DBObject "+coll);


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub


Note: The Mongo object instance actually represents a pool of connections to the database; you will only need one object of class Mongo even with multiple threads.

To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to.

DB db = m.getDB( "test" );

The database doesn’t have to exist – if it doesn’t, MongoDB will create it for you. Once recalled the Servlet it should output:

Got db
Inserted DBObject player
Now let’s try to query for this collection on the mongo console:
MongoDB shell version: 1.8.1

connecting to: test
> db.player.find()
{ “_id” : ObjectId(“4dd28ad9b71d9d0a37845251”), “name” : “Michael”, “surname” :
“Owen”, “age” : 31, “career” : { “goals” : 100, “matches” : 200 } }
{ “_id” : ObjectId(“4dd28ad9b71d9d0a37845252”), “goals” : 100, “matches” : 200 }{/xtypo_code}

If you want to query Collections from Java you can iterate on the collection names:

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

for (String s : colls) {

To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:

DBCollection coll = db.getCollection("player")

For more information refer to the official documentation: