MongoDB-Java Integration


MongoDB and Java applications

It requires Mongo Java driver for your java code to talk to MongoDB. The sample application mentioned below has been written on Windows 8 operating system. I have used jdk 1.7 here. The sample application is written with eclipse.

Example to connect with MongoDB using java

1)    Make sure your MongoDB server process is up and running (Refer to Introduction for details)
2)    Maven Entry



3)    Code snippet


import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongoDBConnectionTest {

public static void main(String[] args) {
 DBObject testdbo = null;
 try {
    testdbo = connectMongoDB();
 } catch (UnknownHostException e) {
 System.out.println("testdbo - " + testdbo);

     * @return
     * @throws UnknownHostException
private static DBObject connectMongoDB() throws UnknownHostException {
/* Get the mongo client object at default port 27017 */
MongoClient client = new MongoClient(new ServerAddress("localhost",

         * From the mongo connection client get db instance based on database
         * name
DB database = client.getDB("myDatabase");

         * From the mentioned database get the instance of collection which has
         * actual json data stored.
DBCollection coll = database.getCollection("testCollection");

/* Returns a cursor with the entire db rows in a collection. */
DBCursor cur = coll.find();

/* Prints the name of active collection. */

while (cur.hasNext()) {
/* DBObject is a single row in a db collection. */
DBObject dbo1 =;
/* Prints current row from the cursor. */
/* prints the entire key used within a row */

/* Finds the first row from the database collection */
DBObject dbo = coll.findOne();
return dbo;

We assume here that you have used introduction section of this article to install MongoDB and setup of basics e.g database, collection etc has been done.

Please share your comments.

Previous articleServlet Example
Next articledoGet() vs. doPost()
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.


  1. so this means if we load java driver along with mongo DB and add configuration as mentioned above, we are all set to use this DB?