Getting started with mongoDB and Python

Post to Twitter

Today I’m going to cover getting started with mongoDB using Python. From the mongoDB website: Mongo (from “humongous”) is a high-performance, open source, schema-free document-oriented database. mongoDB is written in C++.

To use mongoDB you need to have one of these available to you:
1. A computer running Linux
2. An Apple computer running OS X
3. A computer running Windows with some sort of virtual machine software capable of running Linux

UPDATE: Thanks for Kristina (See comments below) to point out there are Windows binaries as well, you can find them here.

Note: If your using Ruby then check out this article.

I’m using Windows Vista with VMWare Workstation to run Ubuntu 9.04 (Desktop).

Installing mongoDB is a simple process and the detailed instructions are found here. I used the Linux 32-bit option and had to install Curl (apt-get) first in order to pull down the MondoDB precompiled binaries.

Installing CURL

Once that was done I created the folder where the data would be persisted:

sudo mkdir -p /data/db

You can then unpack the file wherever you wish:

tar xzf mongodb-linux-i686-latest.tgz

Ok, now I simply started mongoDB the background and let it run with the defaults:

./mongodb-xxxxxxx/bin/mongod &

When that is up and running we can start doing some testing right away. Lets put some data into mongoDB and see if we can get it back out. From another terminal window try this (make sure to run the mongo program from the bin folder where you extracted it to):

db.mystorage.save( { "message":"Hello World"} )
db.mystorage.findOne()

You should see some results now, in particular the message we just entered.

Starting the interactive console

It seems to be working so lets move onto getting Python talking to this. The documentation on mongoDB’s website is very good and the Python docs are no exception, getting the MongoDB Python binding installed is very easy.

To install from a terminal prompt simply type:

easy_install pymongo

Note: You might need to install the Python setup tools first for easy_install to work, if so Ubuntu will prompt you to do that when you attempt to run the above command.

From here the mongoDB Python tutorial is pretty straight forward and you should look it over. I’ll write a little Python sample file to test it out.

from pymongo.connection import Connection
connection = Connection("localhost")

db = connection.foo

doc1 = {"timestamp":001, "msg":"Hello 1"}
doc2 = {"timestamp":002, "msg":"Hello 2"}
doc3 = {"timestamp":003, "msg":"Hello 3"}

db.foo.save(doc1)
db.foo.save(doc2)
db.foo.save(doc3)

cursor = db.foo.find()
for d in cursor:
	print d

First we create our connection to mongoDB on the localhost to the default port of 27017 (this can be modified if needed). Next we create some items to store in mongoDB and call the save method on those. Finally we create a cursor to hold the results of a find call and then iterate through the results printing them to the console.

Querying the results

Lets try a more advanced query no which also cleans up mongoDB of any old records.

from pymongo.connection import Connection
connection = Connection("localhost")

db = connection.foo

for d in db.foo.find({"timestamp": {"$gte" : 2}}):
	print d

db.foo.remove({})

With the data that was entered prior we can query it back out except this time we use the “greater than or equal to” capability “$gte”. So anything greater than or equal to 2 in the timestamp will be returned like this:

A more complex query

The last line of code simply cleans out the database for us:

db.foo.remove({})

That’s all there is to it. Don’t forget to visit the Python mongoDB API for the latest updates and enhancements.

Post to Twitter

This entry was posted in MongoDB, Open Source, Python, Ubuntu. Bookmark the permalink.

8 Responses to Getting started with mongoDB and Python

  1. Kristina says:

    Just so you know, there are also binaries available for Windows 32-bit and 64-bit at http://www.mongodb.org/display/DOCS/Downloads. The “install” isn’t listed on the Quickstart page, but you can just unzip them and run.

  2. Chad Lung says:

    @Kristina,

    Excellent, thanks for the tip. I’m going to update the article.

    Chad

  3. Matthew Greenberg says:

    The setup really helped me going… I am running Ubuntu 9.10 64 bit version… The one thing missing in the page is that non root users will not be able to access /data/db directory and mongod will fail to run… It needs to be mentioned that by chmod -R 777 /data/db will solve this issue…

    Matt

  4. Jeff McNeil says:

    Instead of doing a -R 777, you would be better off specifying a different directory for your data files via ‘–dbpath=something_under_dollar_home.’ The server should still run on the default port as 27017 isn’t privileged.

  5. Larus says:

    > 2. A Mac running OS X

    So, Mac is not a computer?

  6. You can use wget, which is installed by default on Ubuntu, instead of installing curl.

    just wget and the url of whatever you want to download

  7. Helen Neely says:

    I love your sample tutorial on getting started with MongoDB. However, some of the images you linked to could not be accessed – permission denied. You may want to fix them.

    Nice post BTW.

  8. Chad Lung says:

    @Helen,

    There is protection on the images as I’ve had a lot of people leeching articles from my blog lately.

    Chad

Comments are closed.