Using MongoLab with Codenvy

Click this Factory to launch a project connected to MongoLab. You will need to insert your own MongoLab credentials into the source code after the project opens.


This tutorial explains how to integrate MongoLab with Codenvy. MongoLab provides MongoDB hosting on all the major cloud platforms — Amazon, Google, Joyent, Rackspace, and Windows Azure. This tutorial is with a Java project that makes use of MongoDB Java drivers.

Register With MongoLab

The Java drivers will make a call to MongoLab with a URL that requires MongoLab authentication.
MongoLab registration: https://mongolab.com/signup/
MongoLab docs: http://docs.mongolab.com/
MongoDB Java driver APIs: http://api.mongodb.org/java/current/
MongoDB docs: http://docs.mongodb.org/manual/

Create a Project

Now, login to your Codenvy workspace and create a WAR project named as ‘MongoLabSample’. This will have the following structure:
mongolab-structure

Create a pom.xml File

Use maven to add the MongoDB driver to your application:

  <dependencies>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>2.11.4</version>
    </dependency>
  </dependencies>
    
  <repositories>
     <repository>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
      <id>central</id>
      <name>Maven Repository Switchboard</name>
      <url>http://repo1.maven.org/maven2</url>
     </repository>
  </repositories>

This will include the driver jar in your project as follows:
mongolab-dependencies

Create a Java Class

Now create a Java class named MongoLab.java that will establish a MongoDB connection, create a MongoDB collection, insert data to the collection, update the collection and then retrieve the data to display the data on your console logs and then drop the collection and then close the connection. All this is done using the MongoDB Java driver API methods that make use of MongoDB queries. All this is done inside the method onInitialize() in the sample source Java class.

   public void onInitialize() throws UnknownHostException {

        // Create seed data
        final BasicDBObject[] seedData = createSeedData();
        
        // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
        MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db");
        MongoClient client = new MongoClient(uri);
        DB db = client.getDB(uri.getDatabase());
        
        /**
         * First we'll add a few songs. Nothing is required to create the
         * songs collection; it is created automatically when we insert.
         */
        DBCollection songs = db.getCollection("songs");
        songs.insert(seedData);
       
        /**
         * Then we need to give Boyz II Men credit for their contribution to
         * the hit "One Sweet Day".
         */
        BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day");
        songs.update(updateQuery, new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men")));
        
        /**
         * Finally we run a query which returns all the hits that spent 10
         * or more weeks at number 1.
         */
        BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte",10));
        BasicDBObject orderBy = new BasicDBObject("decade", 1);

        DBCursor docs = songs.find(findQuery).sort(orderBy);

        while(docs.hasNext()){
            DBObject doc = docs.next();
            System.out.println(
                "In the " + doc.get("decade") + ", " + doc.get("song") +
                " by " + doc.get("artist") + " topped the charts for " +
                doc.get("weeksAtOne") + " straight weeks."
            );
        }
        
        // Since this is an example, we'll clean up after ourselves.
        songs.drop();
        
        // Only close the connection when your app is terminating
        client.close();
   }

Create an index.jsp File

Your Codenvy project will have an index.jsp which will invoke the Java class -

<%
    com.codenvy.MongoLab mongoLab = new com.codenvy.MongoLab();
    mongoLab.onInitialize();
%>

Now you build and run your Codenvy project and the response will be displayed in the console logs:

mongolab-output

You can view your MongoDB instance to confirm the data set up that your application created and updated. Enjoy!