Skip to main content

NoSQL Databases - MongoDB first cut

A few days ago I tried MongoDB, my first encounter with what is called a NOSQL Database. No, it does not mean 'no' 'sql', rather Not only SQL, anyway I thought I would try mongodb, out of the many available there. It has both the document-oriented database design and ability to be accessed from Javascript, both features I really like. However, since I spend most time in Java, I thought I would start there.

First, let me tell you you should try their web console before writing a line of code or downloading anything because it's a really good self-run tutorial, that lets you type real commands and get real output all from the browser! pretty awesome...

Anyway, here is what I did to get started.
1. Download mongodb from http://www.mongodb.org/
2. Create working dir for MongoDB to use as data directory
3. Open favorite IDE or editor, and start writing test, yes Test, not source, in the spirit of Test Driven Development.
4. In test package, create test such as:

    @BeforeClass
    public static void setup() {
        db = new MongoDB(); db.connect(); // connect to mongodb
        conn = db.connectToDB("test"); // connect to a db called 'test', will be auto created
    }

    @AfterClass
    public static void close() {
        db.close();
    }

    @Before
    public void createdb() {
        coll = conn.getCollection("artifacts"); // fetch a collection called 'artifacts', will be autocreated
    }

    @After
    public void cleanup() {
        coll.drop(); // remove table
    }

    @Test
    public void testConn() {
        assertThat(conn.getName(), is("artifacts"));
        assertThat(conn.getCollectionNames().size(), is(0));
    }

Self explanatory, but shows how easy it is to get started with it.

Run this test, it will fail of course! Now on to the green of TDD...

Now, to make this test pass, we need to do two things : Create the objects we use in the tests, and start MongoDB database server.

First, in a source package, add the class MongoDB which would be like:

import com.mongodb.Mongo;
import com.mongodb.DB;

public class MongoDB {
    private Mongo m = null;

    public void connect() {
        try {
            m = new Mongo();
        } catch (Exception e) {
        }
    }

    public DB connectToDB(String name) {
        DB db = m.getDB(name);
        return db;
    }

    public void close() {
        m.close();
    }
}



Then start MongoDB as:
With a custom data directory (otherwise it assumes a weird location like /data), such as
   >     mongod --dbpath=/local/test/mongodb


Voila, run the test now and it should pass.

You noticed that I tested for the size of collections to be zero, not 1, because the collection 'artifacts' is not created until something is inserted into it.
Also, note that /local/test/mongodb acts as the data directory. for automated tests, you can create this dir in a temp dir, then delete it at the end of testing, which will require shutdown of mongodb. But we won't worry about that now.
Also inspect this directory as you run these tests.

To test this auto create feature of MongoDB, add a test to add a row to the collection, and see if you can get it back, the collection should be auto created.

@Test
    public void testMultipleEntries() {
        for (int i = 0; i < 10000; i++) {
            coll.insert(new BasicDBObject().append("i", i).append("j", i / 2)
                    .append("k", i * 2));
        }
        assertEquals(10000, coll.count());
    }


Pretty straightforward! The BasicDBObject is a Document object. In MongoDB a document is a record, much like a row is in a relational database. The insert() line basically inserts a document with fields 'i' 'j', 'k', into the collection 'artifacts', and with the use of builder pattern you can add as many append()s to keep inserting columns

So what are inserting in each loop iteration looks like:
{ "_id" : { "$oid" : "4dd076881368c78a6cfbdf96"} , "i" : 0 , "j" : 0 , "k" : 0}

If you want to see this formatted document entry, add something like
         System.out.print(coll.findOne());
which displays the first document record (or row) of the collection in JSON format

Comments

  1. I was at a MongoDB meetup the other day, there were a few topics on how people have used it forward various purposes.

    http://www.meetup.com/Boston-MongoDB-User-Group/events/25767451/

    One of the interesting ones for me was the geolocation support usage in combination with a Bing maps based application, as geospatial indexing is built in to MongoDB.

    Rather than me try to explain it, here is the link to the official doc:

    http://www.mongodb.org/display/DOCS/Geospatial+Indexing


    The other interesting talk was on rapid prototyping with MongoDb and a database, with practically nothing in between. While not suitable for production for security reasons, it looked quite useful to develop the GUI and the client API quickly without coding in the middleware business logic layer. I wonder how this will work when you do start coding the middle layer. Ingress the idea is that this is quick, and MongoDb's json abilities are ideally suited for web apps which are increasingly speaking this dialect.

    One more, in another post...

    ReplyDelete

Post a Comment

Popular posts from this blog

Using Sublime Text build system to open your files in your favorite Mac app

A quick hack on Sublime text when working on Macs is to get the editor to invoke the 'open' command so that you can hit command+B to 'open' the file in your favorite app. My favorite use for it is when editing html files, i want it to open in my favorite browser. On a Mac, 'open' is the equivalent of the default file association in Windows, such as when you click on a text file, you can have it open in your favorite editor. In sublime, go to Tools > Build System Select New build system In the file that opens type this in into the pre-filled section and save the file with a name you want, such as 'open.sublime-build': { "cmd": ["open", "$file"] } Then go back to the file you were editing, Tools > Build System. Now select your newly saved build system. Now every time you hit command + B you get the file to open on Chrome (which is what my Mac is setup by default to open html files with)! Obvi...

How to use function closure to capture common arguments in python

Sometimes you need a function that already 'captures' some information you don't want to repeat when calling it. For example, logging may require you to pass in a lot of contextual information for each call. Instead you can capture the common/unchanging contextual information in a function (using its clsoosure) then call the resulting function with less args (only those that are changing in each call site)   class AClass:   def __init__(self):     self.make_log_msg = lambda m: f"a={self.a}, b={self.b}, message={m}"  def do_something(self):     doStuff();     logger.info(self.make_log_msg('test message')) In the absence of the make_log_msg() function you would need to pass all of a,b,c into every logging function call as in self.make_log_msg(self.a, self.b, message) .  This is possible because make_log_msg returns a function (lambda function in this case) that already captures the values self.a and self.b in its closure at the t...

Two cool ways to center content in CSS

You may have seen this question, center a div, or whatever, in interviews or other places. I am sure there are other approaches than I am sharing here, but I found these two cool ideas from multiple places (see refs at the end). These are not my original ideas so I will be sure to share where I learned these from:   Using display:flex  Make sure you know how flex works, but to do centering with flex, it's ridiculously simple: div .container { display : flex ; justify-content : center ; /* horizontal alignment */ align-items : center ; /* vertical alignment */ flex-direction : column ; /* since we are doing a vertical column */ padding : 1rem 3rem ; /* not related to centering */ }  Now everything inside <div class="container"> </div> will be centered in both directions! Using display:grid  You are so going to thank for me this one, you are welcome. This one is so simple it does not even need an explanation does it?   div .conta...