MongoDB

MongoDB (said to be derived from humongous) is one of the important NoSQL databases used now. NoSQL can be read as no relations or sometimes Not only relations. Drawback is that NoSQL doesn't hold the ACID properties fully but in areas where humongous data needs to be handled(like facebook) then NoSQL is far more better than relational types. Mongodb follows document oriented storage. Mongodb handles the data as JSON documents (stored as BSON). It is flexible and it can store huge data at ease.

Enough said lets see MongoDB in action in our local machine.

sudo apt-get install mongodb

Now install pymongo (MongoDB api for python).

sudo easy_install pymongo

MongoDB with Flask


"Flask-PyMongo bridges Flask and PyMongo, so that you can use Flask’s normal mechanisms to configure and connect to MongoDB." (courtesy : http://flask-pymongo.readthedocs.org)

Install it via terminal by,

sudo easy_install Flask-PyMongo

Things are pretty easy than it sounds.

First initialize PyMongo on flask:

from flask.ext.pymongo import PyMongo
mongo = PyMongo(app)

Then initialize the connection for example:

from pymongo import Connection  
connection = Connection() 
db = connection.test_database
collection = db.test_collection

Above code use test_database which is a default one in MongoDB.

Accessing mongodb


posts = db.posts
posts.insert(post)

will insert the JSON data 'post' into the database.

db.posts.find() and db.posts.find_one()   will do the work of SELECT.


find_one() only returns one exact result.

for example:

db.posts.find_one({"title": filename})

The above code will return the document whose title field matches the variable filename.
One thing to note is that pymongo provides default '_id' field, but it stores it as a ObjectId. So using strings '1' '2' etc wont work in find function as id searching variables.


MongoDB in Django


If you think flask was easy then Django is super-easy.
A lot of mongodb engines are available. Well i used the tutorial from the following site.

Install Django-nonrel, djangotoolbox and Django MongoDB Engine.

Then make the following changes in DATABASES in settings.py.

DATABASES = {
   'default' : {
      'ENGINE' : 'django_mongodb_engine',
      'NAME' : 'test_database'
   }
}

Thats it. MongoDB works perfectly fine as any other database.



No comments:

Post a Comment