Using MongoDB with Java, JSP and Mongo Java API

MongoDB is leader amongst NoSQL databases and all our Java hosting packages support it. Here is MongoDB Java primer that you can find useful before reaching for comprehensive MongoDB Java API docs.

MongoDB terminology

As the NoSQL term suggests – things are a bit different in MongoDB then in the SQL wolrd. See the table for keywords.

NoSQL Item Description SQL counterpart
database set of collections database
collection set of documents (also referred to as objects) table
document (object) set of fileds row
field a key-value pair column


A key is a name (string) identifier and a value is a basic type. Basic types include string, integer, float, timestamp, binary, a document object, or an array.

To better understand the differences see most common queries in MySQL, Mongo and Mongo Java API dialects.


MySQL: INSERT INTO `Staff` (name, position) VALUES (‘John Doe’,’Senior Java Developer’)
Mongo: db.staff.insert({name:’John Doe’,position:’Senior Java Developer’})
Mongo Java API: staff.insert(new BasicDBObject().append(“name”, “John Doe”).append(“position”, “Senior Java Developer”));


MySQL: SELECT name FROM `Staff` WHERE position = ‘Senior Java Developer’ ORDER BY name DESC
Mongo: db.staff.find({position:’Senior Java Developer’}, {name:1,position:0}).sort({name:-1})
Mongo Java API: BasicDBObject sortOrder = new BasicDBObject();
sortOrder.put(“name”, -1);
staff.find(new BasicDBObject(“position”, “Senior Java Developer”), new BasicDBObject(“name”, 1)).sort(sortOrder)


MySQL: UPDATE `Staff` SET position = ‘Java Team Leader’ WHERE name=’John Smith’
Mongo: db.staff.update({name:”John Smith”}, {$set:{position:”Java Team Leader”}})
Mongo Java API: BasicDBObject newDoc = new BasicDBObject();
newDoc.append(“$set”, new BasicDBObject().append(“position”, “Java Team Leader”));
staff.update(new BasicDBObject(“name”, “John Smith”), newDoc);


MySQL: DELETE FROM `Staff` WHERE position = ‘Senior Java Developer’
Mongo: db.staff.remove({ position: “Senior Java Developer” }, 1)
Mongo Java API: staff.remove(new BasicDBObject().append(“position”,”Senior Java Developer”));

In SELECT note that when excluding a field in projection you cannot pass fields other than the _id field with ‘0’ value. All other (excluded) fields must be absent. Included fields will have ‘1’ value.

As you can see commands of the JDBC API differ a bit from the commands of Mongo shell. In Java/JSP you provide criteria and projection as BasicDBObjects. Refer to Mongo JDBC API for commands and correct syntax.

You will only be able to access data in a database assigned to you and after connecting to it with your credentials. MongoDB will implicitly create a collection when it first saves data to it. RockMongo is popular web based frontend that you can install in your public_html, but usually you will not need to bother as everything can be done from mongo shell.

MongoDB and Java hosting – quick guide

1.  Request MongoDB database creation with a ticket – cPanel does not provide MongoDB management tool

You will get your MongoDB access details (username will be replaced by your hosting username and by the server name where your database is created). For example

== MongoDB setup ==
local connection string:  mongodb://username_mongouser:secret@localhost/username_mongodb
remote connection string: mongodb://
local access example:     mongo -u username_mongouser -p secret localhost/username_mongodb
remote access example:    mongo -u username_mongouser -p secret
database name: username_mongodb
database user: username_mongouser
database user password: secret

2. Download MongoDB JDBC driver to your web app WEB-INF/lib directory

For quick access you can save it to webapps/ROOT/WEB-INF/lib.


3. Run JSP Mongo testing script

Get the JSP testing script, save it as mongodb.jsp in your webapps/ROOT directory (or another webapp driectory where you saved mongo.jar) and update your MongoDB credentials inside. The code follows:

<%@page import="com.mongodb.*" %>
<%@page import="java.util.*,java.text.SimpleDateFormat" %>
String database = "username_mongodb";
String username = "username_mongouser";
String pass = "secret";
char[] password = pass.toCharArray();
String coll = "";

try {
    MongoClient mongoClient = new MongoClient();
    DB db = mongoClient.getDB(database);
    boolean auth = db.authenticate(username, password);

    DBCollection staff = db.getCollection("Staff");
    DBCollection access = db.getCollection("Access");

    if (request.getParameter("Submit") != null && request.getParameter("Submit").equals("Drop collections")) {
        staff.drop(); access.drop();

    out.println("<h4>Collections list</h4>");
        Set<String> colls = db.getCollectionNames();
        for (String s : colls) {
        out.println(s+", ");

    coll = "Access";
    out.println("<h4>" + coll + "</h4>");
    out.println("Collection '" + coll + "' count: "+ access.count() + "<br/>");

    Date date=new Date();
    String dateString = new SimpleDateFormat("yyyy.MM.dd  HH:mm:ss").format(new Date());
    out.println("Current datetime: "+dateString+"<br/>");

    DBObject lastAccess = access.findOne();  // find().limit(1) much faster

    if (lastAccess != null) {
        out.println("<h5>Updating" + coll +"</h5>");
        BasicDBObject newDoc = new BasicDBObject("_id", lastAccess.get("_id")).append("datetime", dateString);;
        out.println("Saved datetime (last access): "+lastAccess.get("datetime")+"<br/>");
    } else {
        out.println("<h5>Inserting " + coll + "</h5>");
        BasicDBObject doc = new BasicDBObject("datetime", dateString);
        lastAccess = access.findOne();
        out.println("Saved datetime (last access): "+lastAccess.get("datetime")+"<br/>");

// using cursor
    coll = "Staff";
    out.println("<h4>" + coll + "</h4>");
    out.println("Collection '" + coll + "' count: "+ staff.count() + "<br/>");

    // prepare query    
    DBObject clause1 = new BasicDBObject("name", "John Doe");
    DBObject clause2 = new BasicDBObject("name", "John Smith");
    BasicDBList clauses = new BasicDBList();
    clauses.add(clause1); clauses.add(clause2);
    DBObject criteria = new BasicDBObject("$or", clauses);

    // if staff documents do not exist - create them
    if (! staff.find(criteria).hasNext()) {
        // insert docs
        out.println("<h5>Inserting " + coll + "</h5>");
            staff.insert(new BasicDBObject().append("name", "John Smith").append("position", "Junior Java Developer"));
        staff.insert(new BasicDBObject().append("name", "John Doe").append("position", "Senior Java Developer"));
        staff.insert(new BasicDBObject().append("name", "Bill Moe").append("position", "Manager"));

    // find and print staff - ordered
    BasicDBObject sortOrder = new BasicDBObject();
    sortOrder.put("name", -1); // order DESC

    DBCursor cursor = staff.find().sort(sortOrder);
    try {
        while (cursor.hasNext()) {
        DBObject object =;
        out.println(object.get("name") + " " + object.get("position") + "<br/>");
    } finally { cursor.close(); }

    // create index
    staff.createIndex(new BasicDBObject("name", 1));  // create index on "name", ascending
    List<DBObject> list = staff.getIndexInfo();
    out.println("<h4>" + coll + " - Indexes</h4>");

    // find and print indexes
    for (DBObject o : list) { out.println(o.get("name")+", "); }

    // find Senior Java Developers
    out.println("<h4>" + coll + " - Senior Java Developers only</h4>");        

    //> db.staff.find({position:"Senior Java Developer"})
    cursor=staff.find(new BasicDBObject("position", "Senior Java Developer"));
    try {
        while (cursor.hasNext()) {
            DBObject object =;
        out.println(object.get("name") + " " + object.get("position") + "<br/>");
    } finally { cursor.close(); }

    // find Staff - updated position
    out.println("<h4>" + coll + " - position updated</h4>");        

    // update a value in doc
    BasicDBObject newDoc = new BasicDBObject();
    // this would replace whole doc instead of updating single value
    // newDoc.put("position", "Java Team Leader");
    newDoc.append("$set", new BasicDBObject().append("position", "Java Team Leader"));
    staff.update(new BasicDBObject("name", "Bill Moe"), newDoc);

    cursor = staff.find().sort(sortOrder);
    try {
            while (cursor.hasNext()) {
            DBObject object =;
        out.println(object.get("name") + " " + object.get("position") + "<br/>");
    } finally { cursor.close(); }

    // delete a doc
    out.println("<h4>" + coll + " - Staff member deleted</h4>");        
    staff.remove(new BasicDBObject().append("position","Junior Java Developer"));

    cursor = staff.find().sort(sortOrder);
    try {
        while (cursor.hasNext()) {
        DBObject object =;
        out.println(object.get("name") + " " + object.get("position") + "<br/>");
    } finally { cursor.close(); }

%><br/><form method="post">
<input type="submit" name="Submit" value="Drop collections">
<input type="button" value="Refresh" onclick="location.href=document.URL;">
} catch(MongoException e) {

4. Run the Java/Mongo tests from your browser

Access and see how it creates and updates documents and collections. To reset the tests click ‘Drop collections’ – it will start from scratch. To see what changes on subsequent calls click ‘Refresh’.

Using Mongo shell

You can use the sent MongoDB details to connect to MongoDB remotely on default port (27017) using you local copy of mongo client. Altenatively you can login via SSH to the server and then use ‘localhost’ as your server name.

As you can see Java hosting with Mongo is as simple as adding JDBC driver into your web application’s WEB-INF/lib or Tomcat’s lib. Still you may need some time to come to grips wih Mongo and Mongo Java API syntaxes.

Further reading:
Spring and MongoDB
SQL and Mongo DB NoSQL
Getting started with MongoDB Java driver

This entry was posted in Databases, Java. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

nine × = twenty seven

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>