Skip to main content

MongoDb : CRUD Operations Using Java

This article will show you how to use Java to perform CRUD operations on MongoDB records.

If you're new to MongoDB, we recommend starting with the Getting Started With MongoDB tutorial.

To begin, we'll establish a Person and Person Images table (a collection in MongoDB) to make CRUD operations in MongoDB easier.

Define Data Structure

The following is the data structure of the 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
  
We'll use these data structures and associated records to develop interactive image galleries and search engine systems in later tutorial posts.

Create maven project

Now, create a 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 Maven based Java project .

Note: What is Maven's purpose? Although Maven is not required, it allows us to avoid manually installing external libraries such as the MongoDB Java library. Maven aids in the reduction of time and effort by adding the library and its version.


Add following snippet inside pom.xml file inside dependencies tag.

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

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


MongoDB connection

MongoClient mongoClient= new MongoClient("localhost",27017);

/**
Other methods to create client
MongoClient mongoClient= new MongoClient();
                    
MongoClient mongoClient= new MongoClient("localhost");
*/

The MongoDb client can be obtained in three ways.
One without any contractor parameters, or others with a server address or port number.

To create database use following snippet.

//create or select database
DB zainabedDB = mongoClient.getDB("zainabed");

If “zainabed” database is not present in MongoDB then it get created.

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.

Select or Create Collection

The collection acts as a table (RDBMS) and in this tutorial it will be Person and Person Images.

Use the following code to create a collection.

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

The code above will either choose the collection or create it if it does not already exist.

Use the following code to get a list of all available collection names for a given database.

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

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 so, first we need to select or create Person Image collection.

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

Later,  we will create person image BasicDBobject as,

//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 have used “_id” field of Person object to create association.

Now this object is ready for insert into db.

//insert person image record into collection
personImagesCollection.save(personImage);

Read MongoDB Records

MongoDB read operation is very simple, we will see possible read operations such as
  • Find single record
  • Find all records using cursor object
  • Find records using condition

Find Single Record:

To find single record from given collection we will 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 will use find() method of collection and it will provide a cursor to iterate through all records.

//print all person records
DBCursor personCursor = personCollection.find();
                    
while(personCursor.hasNext()){
  System.out.println(personCursor.next());
}

Find records using condition object

We will use condition object (BasicDBObject) to filter out desired results.

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

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

To filter that column, we specify a condition object with a field and a value.

Update MongoDB Records

The update method of a collection object is used to update a record.

Two objects are required for the update method, one to filter out the targeted row and the other to alter the value of a specific column.

//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 the "$set" option to update a record, otherwise it will replace the entire row with the given update column values.

Delete MongoDB Records

The remove () method of collection is used to remove a record from a collection.

To filter records that need to be deleted, we'll need a query object.

//remove record
                    
queryObject = new BasicDBObject("email","abc@gmail.com");

personCollection.remove(queryObject);


Conclusion

This post provided a quick overview of how to use MongoDB from Java.

All of these samples and code snippets can be found on the Github page.

Comments

Post a Comment

Subscribe for latest tutorial updates

* indicates required

Popular posts from this blog

Preload Images Using Javascript

Preload Image is technique which helps browser to render images with minimum delay. Today we will see example of image gallery. Gallery contain 5 images which load images one after another whenever user clicks next and back button. This is a basic image gallery scenario which is used in all possible website, then why we need preloaded images for this gallery? Now a day’s most of website becoming faster and user expectation is increasing. Suppose your website doesn’t use preload image technique for gallery and a user visits any image gallery from Google Plus or Facebook and visits your website gallery. Then that user always prefer those websites rather than yours. Why? Because your website load one image at a time. When user click on next button, then only gallery load image and user has wait till it get loaded. To avoid this situation gallery needs to download all images

Spring Boot RestTemplate Guide with Example

What is RestTemplet? RestTemplate is a HTTP Client library that provides basic APIs for executing different HTTP type requests. RestTemplate is one of the HTTP libraries available on the market. The Spring Boot team designed and maintains it. As previously said, it is a client library, which means it may be utilised in our application as a stand-alone dependency. To utilise it, you don't require a complete Spring boot application. It's suitable for use in simple Java applications as well as other frameworks such as Micronaut, Play and others. Setup Add RestTemplate dependency to project, for this tutorial I am creating a simple java application to consume HTTP request and a node application to provide HTTP service. For Gradle build tool Add the following dependency in the build.gradle file . // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web implementation group: 'org.springframework.boot' , name: 'spring-boot-starter-w

CSS: How To Create Custom Scrollbar For Webkit Supported Browsers

In this tutorial, we will learn how to create a custom scroll bar using custom CSS styles. Custom scrollbars are becoming increasingly popular, and I'm excited to learn more about them. A scrollbar can be customised for a variety of reasons. The default scrollbar, for example, can make an app's UI look inconsistent across various versions of windows, thus we can benefit from having a single style here. This tutorial will help to create a custom scrollbar. Let's see how One of the most interesting aspects of these scrollbars is that they may be rendered in a variety of styles for different HTML elements on the same webpage. We will see the implementation of such a scrollbar for Webkit-supported browsers. First we will look at the basic CSS properties of the scrollbar. ::-webkit-scrollbar              ::-webkit-scrollbar-thumb        ::-webkit-scrollbar-track        ::-webkit-scrollbar-button       ::-webkit-scrollbar-track-piece  ::-webkit-scrollbar-cor