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;
	}
}

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 )

Connecting to %s