My experience with MongoDB

The current project I’m on is using MongoDB. MongoDB is a document based database, it stores JSON objects as BSON (Binary JSON objects). MongoDB provides a middle ground between the traditional RDBMS and the NOSql databases out there, it provides for indexes, dynamic queries, replication, map reduce and auto sharding, its open source and can be downloaded here, starting up mongodb is pretty easy.

./mongod --dbpath=/user/data/db

is all you need, where /user/data/db is the path where you want mongo to create its data files. There are many other options that you can use to customize the mongo instance.

Each mongo instance has databases and each database has many collections, mapping back to oracle, mongo database is a oracle schema and mongo collection is a oracle table, The difference is, each collection can hold any type of object, basically every row can be different.

An example connection to the database using java looks like this

   Mongo mongo = new Mongo("localhost");
   db = mongo.getDB("mydatabase");

If the “mydatabase” does not exist, it will be created. When you want to put objects in the database, you need to have a collection which holds the objects.

   users = db.getCollection("applicationusers");

if the applicationusers collection does not exist, it will be created, at this point you are ready to put objects into the collection.

    BasicDBObject userDocument = new BasicDBObject();
    userDocument.put("name", "jack");
    userDocument.put("type", "super");

You create a document by using the BasicDBObject and put attribute names and their values, in the above example name is the attribute and jack is the value, the users.insert takes the document and inserts it into the collection users. At this point you have a JSON object put into the database.

You can query for the object using the mongo query tool or the restfull api mongo provides using the flag –rest, when you start mongodb, visiting should give you

  "offset" : 0,
  "rows": [
    { "_id" : { "$oid" : "4bc9157e201f254d204226bf" }, "name" : "jack", "type" : "super" }
  "total_rows" : 1 ,
  "query" : {} ,
  "millis" : 0

Every object you insert, gets a auto generated id, more about update, delete and complex objects in next blog post.