MongoDb Java Driver


Its very easy to integrate the MongoDB with a java driver …
Download Java Driver
Once downloaded the connection to the mongodb is made using configServer() and other methods are self explanatory.

public class MongoDB {

	private String hostname ="localhost";
	private int port = 27017;
	private String dbStore = "myFirstApplication";
	private DB database;
	private DBCollection collection;
	public MongoDB(){
		
		configServer();
	}

	/**
	 * doing the configuration. By default the collection is set to testing.
	 */
	private void configServer() {
		try {
			Mongo mongo = new Mongo(hostname,port);
			 database = mongo.getDB(dbStore);
			 collection = database.getCollection("testing");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Insert the json object to DB
	 * @param jsonString
	 */
	public void insert(String jsonString){
		DBObject dbobject = (DBObject) JSON.parse(jsonString);
		collection.insert(dbobject);
	}
	
	/**
	 * find the json object using the key.. Not very efficient though
	 * @param key
	 * @param value
	 * @return
	 */
	public DBObject find(String key,String value){
		BasicDBObject query = new BasicDBObject(key,value);
		DBObject dbObject = collection.findOne(query);
		return dbObject;
	}
	
	
	/**
	 * find an object with the unique object id.
	 *  This throws IllegalArgumentException if the object id doesnt exist 
	 * @param objectId
	 * @return
	 */
	
	public DBObject find(ObjectId objectId) {
		BasicDBObject query = new BasicDBObject("_id",objectId);
		return collection.findOne(query);
	}
	/**
	 * delete the json on the basis of key
	 * @param key
	 * @param value
	 */
	public void delete (String key,String value){
		BasicDBObject query = new BasicDBObject(key,value);
		collection.remove(query);
		
	}
	
	/**
	 * delete by the uniqied id given by mongo
	 * @param objectId
	 */
	public void deleteById(ObjectId objectId){
		BasicDBObject query = new BasicDBObject("_id",objectId);
		collection.remove(query);
	}
	/*
	 * update the value of key in json string. First the object is found using "_id"
	 */
	public boolean update(String key,String value,ObjectId objectId){
		BasicDBObject query = new BasicDBObject("_id",objectId);
		DBObject dbObject = collection.findOne(query);
		if(dbObject != null){
			DBObject newObject = new BasicDBObject(key, value);
			DBObject oldObject = (DBObject) dbObject.get(key);
			if(oldObject != null){
				collection.update(dbObject,new BasicDBObject("$set",new BasicDBObject(key,value)));
				return true;
			}
		}
		return false;
	}
}

Rails 3 + MongDB , MongoMapper beginner tutorial


I recently used MongoDB at my work for mobile app and was tempted to try more. So i wrote a simple app in rails to play with it..

Lets assume rails is already installed.

References for tutorial:
MongoDb installation
MongoDB with Rails
Railcast of integrating rails with Mongo

The installation of MongoDB can be done using the first reference.
Lets create a rails project now to record daily expenses.

rails new expense_record --skip-active-record

We need to update the gemfile by adding mongo dependencies:

require 'rubygems'
require 'mongo'

gem 'rails', '3.0.10'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
source 'http://gemcutter.org'

gem "mongo_mapper"
gem "bson_ext", "1.3.1"
gem "bson" ,"1.3.1"
gem  "mongo","1.3.1"

Now run

bundle install

Create a new filemongo_config.rb in config/initializers folder.
Lets add the following code :

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "#expense-#{Rails.env}"

if defined?(PhusionPassenger)
   PhusionPassenger.on_event(:starting_worker_process) do |forked|
     MongoMapper.connection.connect if forked
   end
end

NOTE: here the #expense is the name of the database. By default Mongo listens to 27017 port. Also the database name should not contain “.”, such as “expense1.0” is wrong.

Now lets create an expense model with field “expense_name” “date_spent” “amount”.

rails g scaffold expense expense_name:string date_spent:string amount:integer --skip-migration --orm mongo_mapper

All the classes are created as expected except the model class expense

class Expense
  include MongoMapper::Document

  key :expense_name, String
  key :date_spent, String
  key :amount, Integer

end

Instead of ActiveRecord , MongoMapper is used which behaves pretty much the same.

Now we are good to run the project.

rails s 
<a href="http://localhost:3000/expenses"></a>

Happy coding..