Lennart Koopmann

{ :blog => true }

MongoDB Java driver tutorial

MongoDB is an free and open source, scalable, high-performance, schema-free, document-oriented database which I use as storage engine for Graylog2.

In this short guide I will show you how to do basic tasks with the MongoDB Java driver. Think of this guide as a quick entry to using MongoDB with Java.

Download the current stable MongoDB Java driver here and import it into your Java project.

Let’s create a Singleton that handles our MongoDB connection first:

import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.MongoException;

public class MongoConnection {
    private static MongoConnection INSTANCE;

    private static Mongo m = null;
    private static DB db = null;

    private MongoConnection() {}

    public synchronized static MongoConnection getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MongoConnection();
        }
        return INSTANCE;
    }

    public void connect(String username, String password, String hostname, String database, int port) throws Exception {
        try {
            this.m = new Mongo(hostname, port);
            this.db = m.getDB(database);

            // Try to authenticate.
            if(!db.authenticate(username, password.toCharArray())) {
                throw new Exception("Could not authenticate to database '" + database + "' with user '" + username + "'.");
            }
        } catch (MongoException.Network e) {
            throw new Exception("Could not connect to Mongo DB.");
        }
    }

    public Mongo getConnection() {
        return this.m;
    }

    public DB getDatabase() {
        return this.db;
    }
}

Now connect to the database at startup. For example somewhere in your main():

try {
    MongoConnection.getInstance().connect(
            Main.masterConfig.getProperty("mongodb_user"),
            Main.masterConfig.getProperty("mongodb_password"),
            Main.masterConfig.getProperty("mongodb_host"),
            Main.masterConfig.getProperty("mongodb_database"),
            Integer.valueOf(Main.masterConfig.getProperty("mongodb_port"))
    );
} catch (Exception e) {
    System.out.println("Could not create MongoDB connection: " + e.toString());
    e.printStackTrace();
    System.exit(1); // Exit with error.
}

Your MongoConnection instance is now connected. Because the MongoDB driver has standard built-in connection pooling, this is all you have to do. Default pool size is 10 but you can configure the pool size by using the MONGO.POOLSIZE system property or by passing MongoOptions to the Mongo constructor. The MongoOptions parameter that controls the pool size is connectionsPerHost.

Selecting a collection Let’s call our collection “messages”. If the collection already exists in MongoDB it will just be selected - If not, it will be created automatically:

coll = MongoConnection.getInstance().getDatabase().getCollection("messages");

Now make sure that all indexes you want exist:

coll.ensureIndex(new BasicDBObject("created_at", 1));
coll.ensureIndex(new BasicDBObject("host", 1));
coll.ensureIndex(new BasicDBObject("facility", 1));
coll.ensureIndex(new BasicDBObject("level", 1));

The ensureIndex() method checks if the index exists and add it if not.

Inserting a document Start by creating a new BasicDBObject():

BasicDBObject dbObj = new BasicDBObject();

Now fill the object:

dbObj.put("message", "ohaithar");
dbObj.put("host", "some host");
dbObj.put("facility", 1);
dbObj.put("level",  5);
dbObj.put("created_at", (int) (System.currentTimeMillis()/1000));

…and insert the object into the collection:

coll.insert(dbObj);

Fetching all documents in a collection

DBCursor cur = coll.find();
while(cur.hasNext()) {
    System.out.println(cur.next());
}

Fetching documents using a conditional query

query = new BasicDBObject();
// Find all where 'level' > 3
query.put("level", new BasicDBObject("$gt", 3));
cur = coll.find(query);
while(cur.hasNext()) {
    System.out.println(cur.next());
}

// Connecting conditions: (all docs where ‘level’ > 3 and <= 10) query.put(“level”, new BasicDBObject(“$gt”, 3).append(“$lte”, 10));

Now you got the very basic skills to use the MongoDB Java driver. I recommend further reading the great API docs or asking in #mongodb on Freenode.

Also check out the database package of Graylog2 on GitHub: http://github.com/lennartkoopmann/graylog2-server/tree/master/src/graylog2/database

Useful links: 1. MongoDB Java Language Center 2. The MongoDB Java (1.4) API Docs

Recent comments

Blog comments powered by Disqus