Passionate about data

Data and its implications on software design and development.

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.

1
./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

1
2
   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.

1
   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.

1
2
3
4
BasicDBObject userDocument = new BasicDBObject();
userDocument.put("name", "jack");
userDocument.put("type", "super");
users.insert(userDocument);

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 http://127.0.0.1:28017/mydatabase/users/ should give you

1
2
3
4
5
6
7
8
9
{
  "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.