MongoDB Read/Write using a Java Client

Recently I’ve been working on some NoSQL projects using Cassandra and MongoDB. So I just thought of sharing some basic stuff related to those NoSQL stores which will be useful for the beginners. In this very first post I’m going to show you how to write a very simple Java code through which you can write data into a MongoDB store and read from it.

Step 1 : Install MongoDB. Depending on your environment, you can very easily install MongoDB on your machine by following the guidelines given here.

Step 2 : Create a Java project on your favorite IDE and add the MongoDB Java driver into your class path. If you are using a Maven script to build your project, you can add the following dependency into it.

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

Step 3 : In this simple example, first we are going to create a database called “sample” and then add a collection called “book” into it. Then we’ll add 3 pages as documents into that collection. To be used as pages in the book collection, make sure you have 3 text files “page1.txt”, “page2.txt” and “page3.txt” in your classpath. After successfully inserting data into the database, we read the first document back from the database to make sure we’ve correctly inserted data. Here’s the Java code to do this. Read comments at each line to get an idea about what each line does.

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;

import java.io.IOException;
import java.io.InputStream;

public class MongoSampleClient {

    public static void main(String[] args) {
        try {
            // create a MongoClient by connecting to the MongoDB instance in localhost
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // drop database if it already exists
            mongoClient.dropDatabase("sample");
            // creating a db named "sample" and a collection named "book"
            DB db = mongoClient.getDB("sample");
            DBCollection bookCollection = db.getCollection("book");
            // insert the 3 pages of the book into the collection
            for (int i = 1; i < 4; i++) {
                BasicDBObject doc = new BasicDBObject("pageId", "page" + i).
                        append("content", readFile("page" + i + ".txt"));
                bookCollection.insert(doc);
            }
            // read the first doc to make sure that we've inserted correctly
            DBObject firstDoc = bookCollection.findOne();
            System.out.println(firstDoc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Reads the specified file from classpath
     */
    private static String readFile(String fileName) throws IOException {
        // get the input stream
        InputStream fileStream = MongoSampleClient.class.getResourceAsStream("/" + fileName);
        // create a buffer with some default size
        byte[] buffer = new byte[8192 * 2];
        // read the stream into the buffer
        int size = fileStream.read(buffer);
        // create a string for the needed size and return
        return new String(buffer, 0, size);
    }
}

You’ll see the following on your console, which is the first document on your new collection.

{ "_id" : { "$oid" : "519f6c1f44ae9aea2881672a"} , "pageId" : "page1" , "content" : "your page1 content" }

Step 4 : Finally you can see the content you inserted above through the MongoDB console by using following commands.

isuru@isuru-w520:~$ mongo

MongoDB shell version: 2.0.4
connecting to: test
> 
> use sample
switched to db sample
> 
> db.book.find()
{ "_id" : ObjectId("519f6c1f44ae9aea2881672a"), "pageId" : "page1", "content" : "your page1 content" }
{ "_id" : ObjectId("519f6c1f44ae9aea2881672b"), "pageId" : "page2", "content" : "your page2 content" }
{ "_id" : ObjectId("519f6c1f44ae9aea2881672c"), "pageId" : "page3", "content" : "your page3 content" }
>

That’s it. In the next post on MonogoDB we’ll be looking at how to use MongoDB Map-Reduce functionality on top of the “book” collection we created above.

Advertisements

About isurues
Age : 24 Date of Birth : 05.11.1984 Country : Sri Lanka

One Response to MongoDB Read/Write using a Java Client

  1. Pingback: MongoDB Map-Reduce Sample | Isuru Suriarachchi's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: