Skip to main content

MongoDb : CRUD Operations Using Java

This tutorial will help you to perform CRUD operation on MongoDB records using Java.

If you unfamiliar with MongoDB then please visit Getting Started With MongoDB tutorial.

To begin with this tutorial we will create Person and Person Images table  (collection in MongoDB) to simplify the MongoDB CRUD operations.

1. Define Data Structure

Following are data structure of Person and Person Images table (collection in MongoDB) 

Int (primary)

Person Images
In later tutorial posts we will use these data structures and their records for building interactive image gallery and search engine system.

2. Create maven project

Now create new project in eclipse and select

  • File -> New -> Other -> Maven Project -> Next
  • Select maven-archetype-quickstart
  • Select Next
  • Type Group Id, Artifact Id and Package name
  • And select Finish

This will create Java project including Maven.


Why we need Maven? Maven is not necessary, but by using Maven we can avoid installation of external library like MongoDB java library. Maven helps to include library and its version, which reduces time and efforts.

3. Download Mongo Java Driver using Maven pom.xml

Add following code inside pom.xml file between dependencies tag



You can find any dependency (java library and drivers) and its version for Maven on

4. Create MongoDB connection

    // MongoClient mongoClient= new MongoClient();
    // MongoClient mongoClient= new MongoClient("localhost");
    MongoClient mongoClient= new MongoClient("localhost",27017);
There are three method to get MongoDb client, one without any contractor parameters, or others with server address or port number.

5. Select or Create Database

To create database use following code

    //create or select database
    DB zainabedDB = mongoClient.getDB("zainabed");
If “zainabed” database is not present in MongoDB then it get created otherwise it get selected.

6. Print All Available Database

    // print all database names
List<String> databaseNames = mongoClient.getDatabaseNames();

for (String dbName : databaseNames) {
  System.out.println("Database : " + dbName);

It will print all database names presents in MongoDB.

7. Select or Create Collection

Collection acts as Table (RDBMS), in this tutorial it will be Person and Person Images.

To create collection use following code

    // select or create collection
    DBCollection personCollection = zainabedDB.getCollection("person");

above code will select the collection or if it does not exist then create it.

To know all available collection names for selected database use following code

// print all collection names
Set<String> collectionNames = zainabedDB.getCollectionNames();
for(String collection : collectionNames){
       System.out.println("collection : " + collection);

8. Create Record (Person)

BasicDBObject is used to create a row object which get inserted into collection.

Following code inserts a row into Person collection.

//create person record
BasicDBObject person = new BasicDBObject()
                     .append("description","Software Developer")
                     .append("birthdate",new SimpleDateFormat("yyyy-MM-dd").parse("1985-03-13"))
                     .append("job","Software Developer")
//insert record into collection;

Now we will insert a record inside Person Image collection.

To do this first we need to select or create Person Image collection

//select person images collection
DBCollection personImagesCollection = zainabedDB.getCollection("person_images");

After this we create person image BasicDBobject.

//create person image record
BasicDBObject personImage = new BasicDBObject()
                     .append("person_id", person.get("_id"))
                     .append("image_path", "/23gfd945j4k4.png")
                     .append("width", 400)
                     .append("height", 400)
                     .append("aspect_ration", 1.0)
                     .append("like", 1000)
                     .append("dislike", 45);

Here we used “_id” field of Person object

Now this object is ready for insert operation

//insert person image record into collection;

9. Read MongoDB Records

MongoDB read operation is very simple, this tutorial will illustrate following read operations

  • Find single record
  • Find all records using cursor object
  • Find records using condition

Find Single Record:

To find single record from given collection we use find() method of collection object.

// find single record
DBObject result = personCollection.findOne();

It will print single result object.

Find All Records Using Cursor Object

To fetch all person records we use find() method of collection and DBCursor to iterate each person records.

//print all person records
DBCursor personCursor = personCollection.find();

Find records using condition object

We use condition object (BasicDBObject) to filter the result

//condition object
BasicDBObject coditionObject = new BasicDBObject("job","Software Developer");

//find with condition
result = personCollection.findOne(coditionObject);

Here we specify condition object with field and value to filter that column.

10. Update MongoDB Records

To update record we use update method of collection object.

Update method requires two objects, one to filter out targeted row and other to update particular column's value.

//update record
BasicDBObject queryObject = new BasicDBObject("username","zainabed");
BasicDBObject updateObject = new BasicDBObject("$set", new BasicDBObject("email",""));
personCollection.update(queryObject, updateObject);


Here we used “$set” option to update a record, otherwise it will replace entire row with given update column values

11. Delete MongoDB Records

To delete a record from collection we use remove() method of collection.

It requires query object to filter rows that we need to delete.

//remove record
queryObject = new BasicDBObject("email","");

Download source code from Github


Post a Comment

Popular posts from this blog

AngularJs Tutorial: Getting Started

This tutorial will help you to create a dynamic web application using power of AngularJs. ·   What is AngularJs AngularJs is javascript MVC framework (maintained by Google) which molds static HTML application to dynamic web application. That was a brief introduction, you can find more information on Wiki and AngularJS Site . AngularJs follows MVC pattern to separate out model from view and manage it by controller. See this image Goal of using AngularJs is to convert static HTML template to dynamic (Angular) template.   ·   How to convert static template to dynamic (Angular) Template Now consider the following static HTML template which contain list of movies title. <html> <head></head> <body>   <h1>Upcoming Movies</h1> <ul>     <li>       <span>Godzilla</span>     </li> <li>       <span>Batman vs Superman</span>     </li> <li>       <span>Sta

Abstract Factory design pattern analysis

What is Abstract Factory design pattern?     The intent or definition of Abstract Factory is “ Provide an interface for creating families of related or dependent objects without specifying their concrete classes ” It is kind of an obscure definition, in order to understand it we need to break it into meaningful pieces. 1.  " Provide an interface "  When we talk about Abstract Factory we talk about interface not abstract class , Basically this design pattern gives us an Interface, like Interface in Java, C# , Typescript (abstract class).    Why interface?  Whenever we talk about any design pattern, it emphasizes more on how we are going to use it rather than implement it. Interface is always the right type to prefer because concrete class creates tight coupling whereas an interface isolates it from the rest of the system. At runtime we can get different solution, without updating our code. For example interface SecurityFactory

AngularJs Tutorials : Bootstrap

Every application starts with bootstrap process which initialize application and wire it other with dependencies and configurations. AngularJs is not different from other application. It also starts application with bootstrap process. Following operation happens inside AngularJs bootstrap process. Load application module. Create dependency injector and load dependencies. Compile HTML and create scope for application. All these steps happens inside angular.js scripting file. therefore we need to include it first. we can include it inside HEAD tag or at end of BODY tag. Note: Adding angular.js file at end of body tag will allow browser to load of HTML elements without any delay and afterwards load angular.js and begin bootstrapping process. You can get angular.js source file from <script src= ”” type= ”text/javascript” > AngularJs bootstrap process happens on docum