Hello guys, This is my first post on this blog. In this post i am going to explain how to interact with MongoDB using Java.First we need to install MongoDB using apt-get command in Ubuntu.

Once we have installed MongoDB, we need a MongoDB jar file(Driver) which we need to add to our IDE. The jar file can be found on this github repository:-


To add the jar file in IntelliJ follow these steps:-

File -> Project Structure  -> Module -> Dependencies -> Add-> Project Library -> Attach Jar

Once we have added the jar file we can start coding.

Making a Connection

To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to.The database doesn’t have to exist – if it doesn’t, MongoDB will create it for you. The code below is used to initialize the connection:-

MongoClient mongoClient = new MongoClient( "localhost" );
DB db = mongoClient.getDB("databasename");

Getting a Collection

To create/get a collection we can use the getCollection(String collectionName) method.
We can specify whatever collection name we want to use.

DBCollection coll = db.getCollection("CollectionName");

Inserting Documents

To insert the document we first create a “BasicDBObject” Object and append the JSON style key-value pair and execute insert method on the collection like this:-

BasicDBObject doc = new BasicDBObject("name", "MongoDB"). append("type", "database"). append("count", 1). append("info", new BasicDBObject("x", 203).append("y", 102)); 

Fetching the Documents

In order to fetch all the documents in the collection, we use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out we can use :

DBCursor cursor = collection.find();
try {
   while(cursor.hasNext()) {
} finally {

Deleting the document.

You first fetch the ID of the document which you want to delete. After getting the ID we use query.put() method and then use collection.remove() method to delete the document. The code to demonstrate this is given below:

System.out.println("Enter the ID of the document you want to delete");
String delid = br.readLine();
BasicDBObject query = new BasicDBObject();
query.put("ID", delid);

This was all about MongoDB. I hope it helped you. Thank you.