Tuesday, December 18, 2012

Getting Started w/ Mongo DB in Linux using Java


The url below contains the information for installing mongo. The steps outline configuring apt to install the package. Following these steps will get mongo running and the ability to do CRUD via command line. You have to get a driver for the language of choice in order to do CRUD via code.


Installation Steps:

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/


Command Line Interface

Mongo’s commands and the like can be found here. The command line interface is pretty straight forward:
http://docs.mongodb.org/manual/crud/


Starting mongo:

sudo service mongodb start


Stopping mongo:

sudo service mongodb stop


Restarting mongo:

sudo service mongodb restart

Connecting to mongo:

mogo

Java Driver

You will need a driver to access MongoDB programmatically. Drivers exist for most languages. The tutorial on Mongo's website has some of this information. Note that the tutorial looks dated. It looks to be using objects that no longer exist in the current version of the driver. This adds confusion so best to avoid the tutorial to get started. I have included some brief code to setup a connection and do some simple CRUD in Mongo. Note that it is not production ready.

http://www.mongodb.org/display/DOCS/Java+Language+Center#JavaLanguageCenter-Basics


Adding the Java Driver with Maven

Just add the dependency below to your Maven file. Maven will take care of getting the jar in. This url will tell you the latest version Maven supports: http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver


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


Code Example


import com.mongodb.*;  
 public class MongoUserDataAdapter {  
   private Mongo mongo = null;  
   private DB db = null;  
   private String serverAddress;  
   private int port;  
   private String databaseName;  
   private String collectionName;  
   /***  
   * this should be handled via config.  
   */  
   public MongoUserDataAdapter(){  
     this.serverAddress = "localhost";  
     this.port = 27017;  
     this.databaseName = "sebsTestDb";  
     this.collectionName = "users";  
   }  
   /***  
    * inserts the user into the collection in mongodb.  
    * @param user  
    * @return a user.  
    */  
   public User createUser(User user) {  
     User result = null;  
     try{  
       // mongo will create this if it doesn't exist.  
       DBCollection collection = db.getCollection(this.collectionName);  
       BasicDBObject document = this.createBasicUserDBObject(user);  
       WriteResult writeResult = collection.insert(WriteConcern.SAFE, document);  
       String error = writeResult.getError();  
       if(error.isEmpty()){  
         result = user;  
       }  
       // ToDo: have mongo set the Id.  
     }  
     catch (Exception ex){  
                //ToDo: log this  
     }  
     return result;  
   }  
   /***  
    * creates a DB document representation of user.  
    * @param user  
    * @return  
    */  
   private BasicDBObject createBasicUserDBObject(User user){  
     BasicDBObject document = new BasicDBObject();  
     document.put("id", user.getId());  
     document.put("email", user.getEmailAddress());  
     document.put("password", user.getPassword());  
     document.put("firstName", user.getFirstName());  
     document.put("lastName", user.getLastName());  
     return document;  
   }  
   public User getUser(String email) {  
     DBObject result = null;  
     DBCursor cursor = null;  
     try{  
       DBCollection collection = db.getCollection(this.collectionName);  
       BasicDBObject query = new BasicDBObject("email", email);  
       cursor = collection.find(query);  
       while(cursor.hasNext()){  
         result = cursor.next();  
       }  
     }  
     catch(Exception ex){  
          // todo: log this  
     }  
     finally{  
       cursor.close();  
     }  
     User user = null;  
     if(result != null){  
       Long id = (Long)result.get("id");  
       String address = (String)result.get("email");  
       String password = (String)result.get("password");  
       String firstName = (String)result.get("firstName");  
       String lastName = (String)result.get("lastName");  
       user = new User(id, address, password, firstName, lastName);  
     }  
     return user;  
   }  
   /***  
    * Connects to the monogdb  
    * @return false if some kind of exception.  
    */  
   public boolean connect(){  
     // this needs to be refactored out into properties where appropriate.  
     boolean success = true;  
     try{  
       // this opens the connection  
       this.mongo = new Mongo(this.serverAddress, this.port);  
       // mongo will create the database if it doesn't exist.  
       this.db = mongo.getDB(this.databaseName);  
     }  
     catch(Exception ex){  
       //ToDo: Log  
     }  
     return success;  
   }  
   public boolean close(){  
     boolean success = true;  
     try{  
       if(this.mongo != null){  
         this.mongo.close();  
       }  
     }  
     catch(Exception ex){  
       // ToDo: log  
       success = false;  
     }  
     return success;  
   }  
 }



References


http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/


http://www.mongodb.org/display/DOCS/Java+Language+Center#JavaLanguageCenter-Basics


http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver

http://docs.mongodb.org/manual/crud/