RkBlog

Hardware, programming and astronomy tutorials and reviews.

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.

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.

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

9 October 2009;

Comment article