Using MongoDB in Python and PHP

MongoDB is a no-relational document database. It main features are high performance and advanced features compared to plain key-value stores. It's written in C++ and available on open license. It's being used as a storage for logs, big binary files and for similar cases.

MongoDB installation

Check if there are mongoDB packages in your distribution repository. If not you can use packages provided by the Mongo team.

MongoDB and Python

For Python there is mongo-python-driver that covers all database features. You can also check some examples how the module can be used. Here is a simple script (the MongoDB server has to be running):
from pymongo.connection import Connection
from pymongo import ASCENDING

# connect to server
connection = Connection("localhost", 27017)

# choose a collection (like a database)
# "test" is the collection name
db = connection.test
# which collection do we use now?
print db.name()

# add some data
db.my_collection.save({"x": 10})
db.my_collection.save({"x": 8})
db.my_collection.save({"x": 11})

# get a row
print db.my_collection.find_one()

# get all rows
for item in db.my_collection.find():
	print item["x"]

# create index
print db.my_collection.create_index("x")

# we use the index to get sorted data
for item in db.my_collection.find().sort("x", ASCENDING):
	print item["x"]

# get 2 entries, skipping 1
print [item["x"] for item in db.my_collection.find().limit(2).skip(1)]

MongoDB and PHP

For PHP there is a complete binary extension, described on Mongo wiki.

  • Get the sources from GIT:
    git clone git://github.com/mongodb/mongo-php-driver.git
  • From terminal go to the souce code folder and compile/install it:
    phpize
    ./configure
    #aclocal
    #autoconf
    make
    make install
    If you get problems with ./configure and make about to old aclocal headers run aclocal and autoconf first.
  • Add to php.ini (/etc/php*/.../php.ini usualy):
    extension=mongo.so;
    After server restart the extension should be visible in the phpinfo.
Here is an example PHP script using the module OO interface:
<pre><?php
$connection = new Mongo();
$db = $connection->selectDB( "testowa" );
$collection = $db->selectCollection( "test" );

$doc = array( "name" => "MongoDB",
   "type" => "database",
   "count" => 1,
   "info" => (object)array( "x" => 203,
       "y" => 102),
   "versions" => array("0.9.7", "0.9.8", "0.9.9")
);

$collection->insert($doc);

print_r($collection->findOne());
You can also check this article: Logging to MongoDb and accessing log collections with Zend_Tool
RkBlog

Python programming, 9 October 2009, Piotr Maliński

Comment article
RkBlog main page Search RSS Contact