MongoDB PHP Tutorial
“MongoDB is a scalable, high-performance, open source, schema-free, document-oriented database. Written in C++” – www.mongodb.org (mongodb.org)
There has been alot of publiclity on NOSQL databases over the last few months. CouchDB, Cassandra and Redis are known to be highly scalable and blazingly fast, yet setup and adoption for hobby developers has been relatively low because there is no need for such high scalability and they are relatively difficulty to get setup.
MongoDB strikes a balance between the familiarity and ease of use of MySQL, and the freeness and performance offered by document storage databases. The database has no set schema so you can add, remove and modify the structure of your documents without having to issue an UPDATE statement.
Installation & Setup
Installing MongoDB is very easy. The only setup required is to create the directory that Mongo stores the data in. In Windows the default location is C:\data\db\ and on *nix it is /data/db/. Once the directory is created, download the appropriate Mongo binary from the downloads page (http://www.mongodb.org/display/DOCS/Downloads) and run the bin/mongod file. Mongo should now be up and running.
Now we need to install the PHP extension for MongoDB. If your on Linux or Mac OS you can use the pecl tool which is packaged with PHP. In the command line type sudo pecl install mongo and it will automatically pull the source, compile it and add the extension entry to php.ini. If your on Windows you will need to download the appropriate binary (http://www.mongodb.org/display/DOCS/Installing+the+PHP+Driver#InstallingthePHPDriver-WindowsInstall) , copy php_mongo.dll to your extension directory and then add the line
extension=php_mongo.dll to the php.ini file. Restart your web server and everything should be up and running.
MongoDB Wrapper
class mongo
{
public $connection;
public $collection;
public function __construct($host = 'localhost:27017')
{
$this->connection = new \Mongo($host);
}
public function setDatabase($c)
{
$this->db = $this->connection->selectDB($c);
}
public function setCollection($c)
{
$this->collection = $this->db->selectCollection($c);
}
public function insert($f)
{
$this->collection->insert($f);
}
public function get($f)
{
$cursor = $this->collection->find($f);
$k = array();
$i = 0;
while( $cursor->hasNext())
{
$k[$i] = $cursor->getNext();
$i++;
}
return $k;
}
public function update($f1, $f2)
{
$this->collection->update($f1, $f2);
}
public function getAll()
{
$cursor = $this->collection->find();
foreach ($cursor as $id => $value)
{
echo "$id: ";
var_dump( $value );
}
}
public function delete($f, $one = FALSE)
{
$c = $this->collection->remove($f, $one);
return $c;
}
public function ensureIndex($args)
{
return $this->collection->ensureIndex($args);
}
}
Using our MongoDB wrapper
With MongoDB installed and running the class written we can now start interacting with some data. We start by instantiating our class, then creating a new database and collection. Both databases and collections are made on the fly. A collection is MongoDB’s equivilant of a table in SQL databases, it just holds data.
$m = new mongo();
$m->setDatabase('query7');
$m->setCollection('data');
Now lets insert some data into the collection. Notice that the value of tutorials is an array. MongoDB supports these data structures natively and values in them can be searched and queried.
$m->insert(array(
'url' => 'http://www.query7.com',
'software' => 'wordpress',
'tutorials' => array('php','javascript','web development'),
));
We can do a simple search and select all documents where url = http://www.query7.com. To find all documents with web development in the tutorials array we would need to set tutorials as an index. As you could imagine this is also straight foward.
$m->get(array('url' => 'http://www.query7.com'));
$m->ensureIndex(array('tutorials' => 1);
$m->get(array('tutorials' = 'php'));
Updates are easy to issue as well. The first parameter is the conditions the data to be updated must meet (similar to WHERE in SQL), the second is the changes we want to make to that data. Notice that the second parameter has the key $set . By using $set we keep the rest of the data in our document (url, tutorials) intact. If we didn’t use $set then the entire document would just contain the key software and the value wordpress2.
$m->update(array('url' => 'http://www.query7.com'), array('$set' => array('software' => 'wordpress2')), true);
Finally we are going to want to delete data. Our delete method takes one argument, the conditions the data must meet.
$m->delete(array('software' => 'wordpress2'));
I hope this has shown you how easy MongoDB is to use. I highly recommend you try MongoDB in your next project.
Further Reading:




