Home > Programming / tutorials > Nosql with Mongo Db Tutorial

Nosql with Mongo Db Tutorial

In the last post we had given a short introduction to nosql

In this post , we will give a small working example with java with mongo db which is a type of nosql database.

Why Mongo DB

  • —It is type of Document database
  • —Written in C++
  • —Development started in 2007
  • —Commercial supported and developed by 10Gen
  • —Supports multiple types of indexing
  • —In built Sharding

What is Sharding ? Sharding is the process of storing data records across multiple machines

sharding

.

Sharding is MongoDB’s approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations.

Development Set Up Mongo

  1. Download and Install Mongo db. http://www.mongodb.org/downloads
  2. Install it on windows or linux.
  3. After installation create a path where you will store data. Don’t forget it is a database so it needs a location where the data can be stored. I created the path in C:\temp2\data\db
  4. Once you have installed go to bin directory and execute this command mongod –dbpath C:\temp2\data\db
  5. For linux users the account that is running mongodb should have write permissions to data/db directory. Run this command sudo chown `id -u` /data/db

Code Example


package demo;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

/**
 * 
 * 
 * @author Vinay
 *
 */
public class HelloMongoDB {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		HelloMongoDB helloMongo = new HelloMongoDB();
		helloMongo.insertData();
		helloMongo.findData();
		helloMongo.updateData();
	}

	/**
	 * An example of find data in mongo db
	 */
	private void findData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country");
		

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");
			DBCursor cursor = db.getCollection("hellomongo").
				find(basic).limit(5);

			while (cursor.hasNext()) {
				System.out.println(cursor.next());
			}
			
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}

	
	/**
	 * An example of update data in mongo db
	 */
	private void updateData(){

		BasicDBObject basic = new BasicDBObject("name" , "USA")
		.append("type", "country")
		
		.append("count", 3)
		.append("states", 
					new BasicDBObject("1" , "MA 3")
						.append("2", "TX 3")
						.append("3", "CA 3"));

		
		try {
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			DB db = mongo.getDB("hellomongo");

			
			BasicDBObject newObject = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)
			.append("states", 
						new BasicDBObject("1" , "MA 1999")
							.append("2", "TX 1999")
							.append("3", "CA 1999"));
			
			db.getCollection("hellomongo").update(basic, newObject);
			

			BasicDBObject newObject2 = new BasicDBObject("name" , "USA")
			.append("type", "country")
			.append("count", 3)	;

			
			DBCursor cursor2 = db.getCollection("hellomongo").
					find(newObject2);
				
				while (cursor2.hasNext()) {
					
					System.out.println(cursor2.next());
					
					
				}
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}
	
	/**
	 * An example of inserting data in mongo db
	 */
	private void insertData(){
		
		try {
			
			//Connect to Mongo DB
			Mongo mongo = new Mongo("127.0.0.1", 27017);
			
			// by default 3 databases are created local, admin, todo
			System.out.println(" Connected "+mongo.getDatabaseNames().toString());
			
			//Created a new database 
			DB db = mongo.getDB("hellomongo");
			
			Set<String> collections = db.getCollectionNames();
			for(String s : collections){
				System.out.println("Collection: " +s);
			}
			DBCollection items = db.getCollection("hellomongo");

			long timeInsertStart = System.currentTimeMillis();
			for(int i= 0; i<100 ; i++){
			
				items.insert(createObjectsToInsert(i));
			}
			long timeInsertEnd = System.currentTimeMillis();
			System.out.println(" Time to Insert --> "+(timeInsertEnd-timeInsertStart));
			
/*			DBObject myDoc = items.findOne();
			System.out.println(myDoc);
*/

			long timeFetchStart = System.currentTimeMillis();
			DBCursor cursor = items.find();
			long timeFetchEnd = System.currentTimeMillis();
			System.out.println(" Time to fetch --> "+(timeFetchEnd-timeFetchStart));
			while (cursor.hasNext()) {
				//System.out.println(cursor.next());
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
			
		}

	}
	
	private static BasicDBObject createObjectsToInsert(int count){
		
		BasicDBObject basic = new BasicDBObject("name" , "USA")
									.append("type", "country")
									.append("count", count)
									.append("states", 
												new BasicDBObject("1" , "MA "+count)
													.append("2", "TX "+count)
													.append("3", "CA "+count));
		
		return basic;
	}
	
}


pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>javaMongoDBExample</groupId>
  <artifactId>javaMongoDBExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>javaMongoDBExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Mongo Db driver -->
     <dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.12.0</version>
	</dependency>
  </dependencies>
</project>

Get the working project from github

Full Documentation

http://docs.mongodb.org/

Helpul Links

  1. No comments yet.
  1. No trackbacks yet.