Up and running MongoDB with python.


MongoDB is a NoSQL database which stores records as documents.MongoDB has some really nice, unique tools that are not (all) present in any other solution.


MongoDB supports generic secondary indexes, allowing a variety of fast queries, and provides unique, compound, and geospatial indexing capabilities as well.

2.Stored JavaScript

Instead of stored procedures, developers can store and use JavaScript functions and values on the server side.

MongoDB supports MapReduce and other aggregation tools.
4.Fixed-size collections
Capped collections are fixed in size and are useful for certain types of data, such as logs.
5.File storage
MongoDB supports an easy-to-use protocol for storing large files and file metadata.

Some features common to relational databases are not present in MongoDB, notably joins and complex multi row transactions. These are architectural decisions to allow for scalability, because both of those features are difficult to provide efficiently in a distributed system.

After installing the MongoDB please run following commands to start the mongoDB server.

$./mongod          for linux or mac users (or)

C:\>mongod       if windows users

Server runs default on port 27017.

next if you want to perform raw database operations open another terminal and type

$./mongo (or) C:\>mongo to launch client  database java script shell.

Actually the documents stored in the MongoDB are in the format of BSON.Python developers only deals with storing  Dictionaries as documents into mongoDB but never look into BSON format,we doubt how things are going fine?.The solution is a driver called pymongo abstracts the conversion of python dictionary into MongoDB valid BSON document.So now we should install pymongo to integrate python and mongodb.

First we can look into how basic MongoDB client java script shell works.

initially the shell looks like this:

MongoDB shell version 2.2.7

connecting to: test


> x = 200
> x / 5;

> “Hello, World!”.replace(“World”, “MongoDB”);
Hello, MongoDB!

> function factorial (n) {
… if (n <= 1) return 1;
… return n * factorial(n – 1);
… }
> factorial(5);

All the above are java script expressions and its functions.So it is a full fledged interpreter.

If you have a database called ‘student’ then we can switch from test db to student db as

>use student

switched to db student


Insertion into MongoDB

First we can create a post and insert it into database.

> post = {“title” : “Naren”,
… “ID” : “10C91A05B3”,
… “date” : new Date()}


Now the record post is saved in the student database.


Retrieving the record from MongoDB


this command returns all the documents in student database.It is equivalent to ‘select * from student’ in SQL.


this command returns only first document from the student database.we can also use criteria for fetching documents.

Note: _id is the default field that will be added by MongoDB for each document we inserts.By fetching you will see additional field in addition to “title”,”ID”,”date”.In this way MongoDB provides default primary key for each document.

If you want to select a record whose name is Naren.then use the following command.



Updating a document in MongoDB

case 1: Adding new field

If we want to insert new field percentage into document then first do



Now document looks like



“date”:”Sunday May 18 2014 09:18:22 PM”,


case 2: modifying existing record


by above command the database search for document whose title is Naren and sets its ID value to 10C91A0501.

‘$set’ is called as modifier,MongoDB is very rich in modifiers.Check MongoDB manual for complete list.


Deleting records in database

> db.student.remove({title : “Naren”})

it removes all the records with title:”Naren”

Note: If you want to remove entire student database collection,then don’t loop for each document.Simply use following command


Above command makes student database empty and it is preferred because of performance issues.

Jump starting the Python and MongoDB

First install the pymongo library for python interpreter.Use  “pip install pymongo” to do that.Once pymongo was installed now we are ready to play with mongoDB.


from datetime import datetime
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
    """connects to mongo db"""
        print "Connected sucessfully"
    except ConnectionFailure,e:
        sys.stderr.write("Couldn't connect:%s"%e)
    assert dbh.connection==c
    print "successfully inserted doc:%s"%user_doc
    print "Now reteiving result"
    for user in fan:
        print user["email"]
if __name__=="__main__":main()

  1. First you should start mongoDB server by typing $./mongod or C:\>mongod.
  2. Don't be afraid by seeing all those dirty imports.Just we required is Connection class from pymongo package.So 'from pymongo import Connection' is required.
  3. Above two steps are compulsory.Now we should get a Connection object to mongoDB so,c=Connection(host,port).Here host=”localhost”,port=27017 by default.
  4. Now we should get a database handle to perform CRUD operations,so dbh=c[‘mydb’].This fetch handle for database mydb.in this database we can store many collections(tables in SQL language).
  5. Now to insert a document called user_doc into collection ‘users’, we simply call dbh.users.insert(user_doc). we don’t need to create a new collection called users.MongoDB automatically creates users.
  6. By retrieving we will get a cursor object here it is “fan”.So for each document user in collection fan we are printing ’email’ .All other imports are for error handling if connection fails,and datetime is for generating date for user_doc.
  7. This is just to give a quick start for you to switch to MongoDB,there are good books on the topic.                                                   For any queries please mail,me.narenarya@live.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s