Connect MongoDB with Java



This post is about how to connect MongoDB server through java. Before that here are some tricks which may be useful to work with MongoDB.

Before running  the MongoDB server, make sure to create following folders in C.


And after running MongoDB server, if you close the window forcibly (Without pressing Ctrl+C),  you won’t be able to run it again. Here is the solution. Go to C:datadb and delete the file “mongod.lock”. 😀

So, here is how to connect MongoDB server using java.
Download the latest mongoDB java driver from  here. Create a  new java project in eclipse. Add a user library to add mongodb  driver.

Then add following to the code.

package com.technodyne.core;


import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class App {

 public static void main(String[] args) {

 try {
 // connect to mongoDB, ip and port number
 Mongo mongo = new Mongo("localhost", 27017);

 // get database from MongoDB,
 // if database doesn't exists, mongoDB will create it automatically
 DB db = mongo.getDB("technodyne");

 // Get collection from MongoDB, database named "yourDB"
 // if collection doesn't exists, mongoDB will create it
 // automatically
 DBCollection collection = db.getCollection("MyCollection");

 // create a document to store key and value
 BasicDBObject document = new BasicDBObject();
 document.put("id", 1001);
 document.put("msg", "hello world mongoDB in Java");

 // save it into collection named "MyCollection"

 // search query
 BasicDBObject searchQuery = new BasicDBObject();
 searchQuery.put("id", 1001);

 // query it
 DBCursor cursor = collection.find(searchQuery);

 // loop over the cursor and display the retrieved result
 while (cursor.hasNext()) {


 } catch (UnknownHostException e) {
 } catch (MongoException e) {



Then run the application. The result is below.

{ “_id” : { “$oid” : “50423e3b28b389ac6e3c3aa7”} , “id” : 1001 , “msg” : “hello world mongoDB in Java”}


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s