QRdvark.com

Introduction To MongoDB And PHP Tutorial

Introduction To MongoDB And PHP Tutorial

  1. Abstract
  2. Installing MongoDB with YUM
  3. Mongo Shell
  4. Collections
  5. PHP MongoDB Extention Installation
  6. SELECT
  7. Add To A Collection( INSERT )
  8. DELETE
  9. UPDATE

Abstract

The name MongoDB was derived from Humongous DB. MongoDB is an open source NoSQL database. MongoDB is developed and commercially supported by the company 10gen.

The focus of the MongoDB is on scalability and performance. MongoDB is a schema-free document-oriented database. This stores data as JSON objects. Unlike traditional SQL database, you don’t need to define a schema

Installing MongoDB with YUM

In this instance we are using CentOS. Feel free to alter as needed for your RPM based distro. There is no real magic here, first we set up the MongoDB YUM repository.

With your favourite editor, create the file /etc/yum.repos.d/10gen.repo and use the below content for the MongoDB YUM repository.

[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0
enabled=1

To see the MongDB packages execute the following

yum --disablerepo="*" --enablerepo="10gen" list available
Available Packages
mongo-10gen.x86_64 2.4.5-mongodb_1 10gen
mongo-10gen-server.x86_64 2.4.5-mongodb_1 10gen
mongo-10gen-unstable.x86_64 2.5.0-mongodb_1 10gen
mongo-10gen-unstable-server.x86_64 2.5.0-mongodb_1 10gen
mongo18-10gen.x86_64 1.8.5-mongodb_1 10gen
mongo18-10gen-server.x86_64 1.8.5-mongodb_1 10gen
mongo20-10gen.x86_64 2.0.8-mongodb_1 10gen
mongo20-10gen-server.x86_64 2.0.8-mongodb_1 10gen

Now, to install the client and server packages

yum -y install mongo-10gen mongo-10gen-server

And now, start the MongoDB server..

service mongod start

Mongo Shell

With the MongoDB server installed, the mongo shell can be used to perform database operations. At the command prompt, simply enter mongo.

mongo
MongoDB shell version: 2.4.5
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user

To insert into MongoDB this is the syntax

doc1 = { name : "my_docs" }; db.sites.insert( doc1 );

And to select the data back again is as simple as using the find method. This is the equivalent of SELECT * FROM sites in SQL.

db.sites.find()
{ "_id" : ObjectId("51d6df419783996ee312ce5f"), "name" : "my_docs" }

Collections

MongoDB introduces the concept of collections. Just as an SQL database table can have multiple rows, so too can a MongoDB collection can have multiple documents. A collection is represented as JSON object, with fields and values represented as key-value pairs and serialized in Binary JSON (BSON) to be stored.

To create a collection is made quite simple. Here we create a collection called products, and insert some data

db.products.insert({ name: 'Toasters', quantity: 10, price: 11.50 })
db.products.insert({ name: 'Cameras', quantity: 3, price: 330.00 })
db.products.insert({ name: 'Jackets', quantity: 30, price: 80.95 })

Now, if you use the find method, you can see all the results from the products collection.

db.products.find();
{ "_id" : ObjectId("51d6e4b69783996ee312ce60"), "name" : "Toasters", "quantity" : 10, "price" : 11.5 } { "_id" : ObjectId("51d6e4bf9783996ee312ce61"), "name" : "Cameras", "quantity" : 3, "price" : 330 } { "_id" : ObjectId("51d6e4d89783996ee312ce62"), "name" : "Jackets", "quantity" : 30, "price" : 80.95 }

Thats fine if we want all the results, but what if we just want products over one hundred dollars?

db.products.find({price: {$gt: 100}})

PHP MongoDB Extention Installation

Because PHP loves you, the MongoDB PHP extension can be installed painlessly with PECL.

pecl install mongo

If you get an error like this..

ERROR: `phpize' failed

The reason is due to a bug in PHP that dates back to 2004 and is flagged as Won't Fix. If your PHP installation is compiled --enable-sigchild, this will cause this error.

The fix.. Recompile PHP without the --enable-sigchild flag. OK, so maybe not so painless.

If all goes well for you, you should be looking at something like this

Build process completed successfully
install ok: channel://pecl.php.net/mongo-1.4.1

DID IT!? DID IT REALLY!!??

I am installing on CentOS and after pecl reported that the installation was successful, I could not find the mongo.so file on the system. The solution is to compile from source. Get a copy of mongo-1.4.1.tgz and use these commands to install.

tar -zxf mongo-1.4.1.tgz
cd mongo-1.4.1
phpize
./configure
make
make install

Be sure to add this line to your php.ini file to ensure the module is loaded.

extension=mongo.so

And so ends the painless installation of php mongo extension

SELECT

Earlier in this tutorial, we created a collection of three products in our MongoDB collection. Here we will use PHP to retrieve the results.


<?php
try {
    
// a new MongoDB connection
    
$conn = new Mongo('localhost');

    
// connect to test database
    
$db $conn->test;

    
// a new products collection object
    
$collection $db->products;

    
// fetch all product documents
    
$cursor $collection->find();

    
// How many results found
    
$num_docs $cursor->count();

    if( 
$num_docs )
    {
        
// loop over the results
        
foreach ($cursor as $obj)
        {
            echo 
'Name: ' $obj['name'] . "\n";
            echo 
'Quantity: ' $obj['quantity'] . "\n";
            echo 
'Price: ' $obj['price'] . "\n";
            echo 
"\n";
        }
    }
    else
    {
        
// if no products are found, we show this message
        
echo "No products found \n";
    }

    
// close the connection to MongoDB 
    
$conn->close();
}
catch ( 
MongoConnectionException $e )
{
    
// if there was an error, we catch and display the problem here
    
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
    echo 
$e->getMessage();
}

?>

From the above code, you should be seing something like this:

Name: Toasters
Quantity: 10
Price: 11.5

Name: Cameras
Quantity: 3
Price: 330

Name: Jackets
Quantity: 30
Price: 80.95

Add To A Collection

Add to a collection is synonymous with the SQL INSERT syntax. Here we add some televisions to our product collection.


<?php
try {
        
// Connect to MongoDB
        
$conn = new Mongo('localhost');

        
// connect to test database
        
$db $conn->test;

        
// a new products collection object
        
$collection $db->products;

        
// Create an array of values to insert 
        
$product = array(
                        
'name' => 'Televisions',
                        
'quantity' => 25,
                        
'price' => 499.99,
                        
'note' => '54 inch flat screens'
                        
);

        
// insert the array
        
$collection->insert$product );

        echo 
'Product inserted with ID: ' $product['_id'] . "\n";

        
// close connection to MongoDB
        
$conn->close();

}
catch ( 
MongoConnectionException $e )
{
        
// if there was an error, we catch and display the problem here
        
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
        echo 
$e->getMessage();
}

?>

In the above code, a simple PHP array has been created which contains the attributes of the product to added (INSERTed) into MongoDB. The actual insertion is simply a matter of using the insert() method. Using the SELECT code from the previous example, should show you the televisions record in the products collection (table).

Delete

Part of any useful CRUD is the ability to delete records. MongoDB provides a very nice remove() method for this which takes an array of product attributes as the criteria for removing a record. Here we remove the Televisions product from the collection.


<?php
try {
        
// Connect to MongoDB
        
$conn = new Mongo('localhost');

        
// connect to test database
        
$db $conn->test;

        
// a new products collection object
        
$collection $db->products;

        
// Create an array of product criteria 
        
$product_array = array(
                        
'name' => 'Televisions'
                        
);

        
$r $collection->remove$product_array, array( 'safe' => true ) );
        echo 
$r['n'] . " documents deleted \n";

        
// close connection to MongoDB
        
$conn->close();
}
catch ( 
MongoConnectionException $e )
{
        
// if there was an error, we catch and display the problem here
        
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
        echo 
$e->getMessage();
}

Of course, there may be many products named 'Televisions', and so, like an SQL database, we use an ID to delete records. By adding the ID to our original SELECT array, we can get the ID's of each product in our collection.


<?php
try {
    
// a new MongoDB connection
    
$conn = new Mongo('localhost');

    
// connect to test database
    
$db $conn->test;

    
// a new products collection object
    
$collection $db->products;

    
// fetch all product documents
    
$cursor $collection->find();

    
// How many results found
    
$num_docs $cursor->count();

    if( 
$num_docs )
    {
        
// loop over the results
        
foreach ($cursor as $obj)
        {
            echo 
'ID: ' $obj['_id'] . "\n";
            echo 
'Name: ' $obj['name'] . "\n";
            echo 
'Quantity: ' $obj['quantity'] . "\n";
            echo 
'Price: ' $obj['price'] . "\n";
            echo 
"\n";
        }
    }
    else
    {
        
// if no products are found, we show this message
        
echo "No products found \n";
    }

    
// close the connection to MongoDB 
    
$conn->close();
}
catch ( 
MongoConnectionException $e )
{
    
// if there was an error, we catch and display the problem here
    
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
    echo 
$e->getMessage();
}

The result set will now show the ID's as follows

ID: 51d6e4b69783996ee312ce60
Name: Toasters
Quantity: 10
Price: 11.5

ID: 51d6e4bf9783996ee312ce61
Name: Cameras
Quantity: 3
Price: 330

ID: 51d6e4d89783996ee312ce62
Name: Jackets
Quantity: 30
Price: 80.95

Now that we have the ID of each product, deleting a product with the ID is quite simple. Here we delete the Cameras from the collection using its ID.


<?php
try {
        
// Connect to MongoDB
        
$conn = new Mongo('localhost');

        
// connect to test database
        
$db $conn->test;

        
// a new products collection object
        
$collection $db->products;

        
// remove a document by ID
        
$product_array = array(
                        
'_id' => new MongoId'51d6e4bf9783996ee312ce61' ),
                        );

        
// delete the record from the collection
        
$collection->remove$product_array );

        
// show that the job is done
        
echo 'Product with ID: ' $product_array['_id'] . " removed successfully.\n";

        
// close connection to MongoDB
        
$conn->close();

catch ( 
MongoConnectionException $e )
{
        
// if there was an error, we catch and display the problem here
        
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
        echo 
$e->getMessage();
}
?>

UPDATE

No CRUD would be complete without a method to UPDATE records. MongoDB provides a simple method to update records using the save() method. As shown in previous examples, MongoDB requires an array of criteria to know which record, or records, to act upon. In this regard, the save() method is no different. In this example, the Jackets will be updated.


<?php

try {
        
// Connect to MongoDB
        
$conn = new Mongo('localhost');

        
// connect to test database
        
$db $conn->test;

        
// a new products collection object
        
$collection $db->products;

        
// the array of product criteria
        
$product_array = array(
                        
'name' => 'Jackets',
                        );

        
// fetch the Jackets record
        
$document $collection->findOne$product_array );

        
// specify new values for Jackets
        
$document['name'] = 'Leather Jackets';
        
$document['quantity'] = 100;
        
$document['note'] = 'Quality Leather Jackets';

        
// save back to the database
        
$collection->save$document );

        
// close connection to MongoDB
        
$conn->close();

}
catch ( 
MongoConnectionException $e )
{
        
// if there was an error, we catch and display the problem here
        
echo $e->getMessage();
}
catch ( 
MongoException $e )
{
        echo 
$e->getMessage();
}
?>
?>

PHP and MongoDB provide many more useful and powerful tools for handling your data. More will be seen here, but this has displayed a simple method (less the pain of PECL) of working with MongoDB using PHP.