Tuesday, June 3, 2014

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) 

Person
id
Int (primary)
username
String
first_name
String
last_name
String
email
String
description
String
birthdate
Date
country
String
state
String
city
String
lat
String
lang
String
job
String


Person Images
id
Int(Primary)
person_id
Int
image_path
String
width
Int
height
Int
aspect_ration
Double
like
Int
dislike
Int
  
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.

Note:

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

<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>2.12.2</version>
</dependency>


Note:

You can find any dependency (java library and drivers) and its version for Maven on http://mvnrepository.com

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("username","zainabed")
                     .append("first_name","Zainul")
                     .append("last_name","Shaikh")
                     .append("email","xyz@gmail.com")
                     .append("description","Software Developer")
                     .append("birthdate",new SimpleDateFormat("yyyy-MM-dd").parse("1985-03-13"))
                     .append("country","india")
                     .append("state","maharashtra")
                     .append("city","pune")
                     .append("job","Software Developer")
                     .append("lat","18.526895")
                     .append("long","73.856101");
                    
//insert record into collection
personCollection.save(person);

  
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
personImagesCollection.save(personImage);
  

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();
System.out.println(result);
  

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();
                    
while(personCursor.hasNext()){
  System.out.println(personCursor.next());
}
  


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);
System.out.println(result);
  

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","abc@gmail.com"));
                    
personCollection.update(queryObject, updateObject);
  

Note:

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","abc@gmail.com");

personCollection.remove(queryObject);
  
Download source code from Github

Zainul Abedin Shaikh

Founder of Zainabed, Passionate about programming. Follow him on Twitter

And if you enjoyed this post, please consider sharing it on Facebook, Google+ or Twitter below