Home arrow PHP arrow MongoDB: A Free Document-Oriented Database

MongoDB: A Free Document-Oriented Database

This tutorial will show you how to use MongoDB with PHP as an alternate database choice.

By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
September 01, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Without a doubt, RDBMS' (Relational Database Management Systems) rule the world of data persistence. Backed by a huge (and growing) number of manufacturers, which cover a plethoric variety of platforms and environments, relational databases are - in most cases - the default mechanism for storing information in a relatively straightforward manner. However, not all is wonderful in the terrain of RDBMS, since the use of tables isn’t always the best way to persist objects (either real or virtual ones).

In many use cases (like persisting blog posts), the storage process suffers from an issue commonly known as impedance mismatch: in simple terms, this means that objects don’t always maintain a 1:1 relationship with a table in a database, making it necessary to implement different persistence strategies in order to map the objects in question to multiple tables.

In response to this issue, (and others, omitted for the sake of brevity), in the last decade a different breed of databases have emerged: object-oriented databases. In reality, object-oriented databases aren’t anything new: (http://en.wikipedia.org/wiki/List_of_object_database_management_systems); what’s really new is that some of them are starting to find a niche in the area of web development.

Want a clear and succinct example of this? Enter MongoDB (http://www.mongodb.org), an open source, document-oriented database written in C++, which will let you store your data in BSON format (short for Binary JSON). What’s more, MongoDB uses concepts like documents and collections, instead of their counterparts, rows and tables, to save data, in this way creating an efficient storage platform that’s both easy to interact with and grasp, without having to deal with the drawbacks of relational tables.

If all of these benefits don’t convince you to take a peek at it, MongoDB provide drivers for a bunch of popular programming languages, including C, C#, Java, Ruby, PHP and so forth (for more information, check here [http://www.mongodb.org/display/DOCS/Drivers]).

Provided that the features offered by MongoDB have caught your attention, in this tutorial I’ll be showing you how to take advantage of them in PHP, so that you can learn how to get things rolling with this lightweight document-oriented database.

First Steps: Installing MongoDB, Creating a Database and a Sample Collection

Before we start out playing around with the goodies offered by MongoDB, it needs to be installed on your machine. To do so, go grab a copy of it here (http://www.mongodb.org/downloads). In this case, I’ll be using the database on Windows, so make sure to download the package that works with your operating system.

Now, unzip the source files and place them in the directory of your choice (mine is C:\mongodb). Once you’ve finished this step, it’s time to start the database daemon. To do this, simply fire up your console, then navigate to the database “bin” directory and issue the command “mongod”, as shown below:
    

If all went well, your console should look similar to the above one. This means that the database server is up and running. Thus, it’s time to create a sample database and a collection, (the equivalent of a table in a relational database), this way we can easily insert, update and delete documents from it.

Again, open a new console window, go to the aforementioned “bin” directory and type “mongo” (this starts the MongoDB client program). Finally, create a new database called “blogs” by writing the command “use blog” in the console, like this:

At this point, the “blogs” database hasn’t been created, since it’s necessary to add to it at least one collection. For demonstrative purposes, we’ll be working with a collection called “posts”, so the next step that must be taken is to populate the collection with some sample documents. This can be done by typing the following in the console:

db.posts.save({ "title""My first post""content""This is the content of the first post""comments": { "comment 1""This is a sample comment""comment 2""This is another sample comment""comment 3""This is yet another sample comment"}})

This not only brings the desired database to life, but it creates the “posts” collection and fills it up with some BSON documents as well. The images below depict this process more clearly:

Finally, add a few more documents to the “posts” collection, as follows:

db.posts.save({ "title""My second post""content""This is the content of the second post""comments": { "comment 1""This is a sample comment""comment 2""This is another sample comment""comment 3""This is yet another sample comment"}})
db.posts.save({ "title""My third post""content""This is the content of the third post""comments": { "comment 1""This is a sample comment""comment 2""This is another sample comment""comment 3""This is yet another sample comment"}})
db.posts.save({ "title""My fourth post""content""This is the content of the fourth post""comments": { "comment 1""This is a sample comment""comment 2""This is another sample comment""comment 3""This is yet another sample comment"} })

So far, so good. At this stage, the sample “posts” collection is ready to be put under test. As I explained at the start, MongoDB can be used with a host of programming languages; however, my goal here is to show you how to utilize it specifically with PHP, therefore in the coming section, I’ll be demonstrating how simple is to setup a script that fetches the set of documents just added to the previous collection.

Getting Started Using MongoDB: Fetching Documents from the Previous Collection

In reality, there’s still one more thing that you need to do before you can use MongoDB with PHP. Yes, as you may have guessed, it’s necessary to install the PHP driver on your testing machine. So, make sure to browse the Windows drivers here (https://github.com/mongodb/mongo-php-driver/downloads) and download the one compatible with your PHP installation. Finally, unzip the .DLL file, place it in your PHP directory extension (mine is C:\php\ext) and add the following line to your php.ini file:

extension=php_mongo.dll

Done. That was the boring part, so now get ready for the fun one! Remember the set of documents that were added to the previous “posts” collection? Well, let me show you how easy is to fetch the first one via the MongoDB PHP API.

The only thing that you must do is simply to write an script similar to this one:

<?php
namespace MongoDB;
// connect to the daemon
$mongo = new Mongo();
// select the 'blog' database
$db $mongo->selectDB('blog');
// select the 'posts' collection
$collection $db->selectCollection('posts');
// fetch the first post from the collection
$post $collection->findOne();
// display the first post
echo 'Id: ' $post['_id'] . '<>; 
Title: ' 
$post['title'] . '<>
 Content: ' 
$post['content'] . '<>';
// display the related comments
foreach ($post['comments'] as $key => $comment) {
echo 
$key ' ' $comment '<>';
}
/* displays the following
Id: 4e443c89e4a8497614dcc8d2
Title: My first post
Content: This is the content of the first post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
*/

That was really simple to code and read. As seen above, the script firstly creates an instance of a “Mongo” class (which establishes a connection to the server), then it selects the “post” database, and finally the “post” collection. Once the collection has been grabbed, the “findOne()” method is used, not surprisingly, for fetching the first document.

Furthermore, if you’re an insightful observer, surely you’ll have noticed that the document now includes a field called “_id”. But, where did this come from? Effectively, MongoDB has automatically created this identifier, which is unique for each document present in the collection. Pretty handy, isn’t it?

All in all, at this stage I’m certain that you understood the driving logic of the previous script. However, fetching the first document of the collection is a process with a rather limited functionality. How about retrieving all the documents? In such a case, this can be done with the brand new “find()” method, which can be put to work in the following way: 

<?php
namespace MongoDB;
// connect to the daemon
$mongo = new Mongo();
// select the 'posts' collection
$collection $mongo->selectDB('blog')->selectCollection('posts');
// fetch all posts from the collection
$posts $collection->find();
foreach (
$posts as $post) {
// display the posts
 
echo 'Id: ' $post['_id'] . '<>
 Title:  . $post['
title'] . '<>
 
Content' . $post['content'] . '<>';
// display the related comments
foreach ($post['
comments'] as $key => $comment) {
echo $key . ' ' . $comment . '
<>';
}
echo '
<>';
}
/* displays the following
Id: 4e443c89e4a8497614dcc8d2
Title: My first post
Content: This is the content of the first post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
Id: 4e443d16e4a8497614dcc8d3
Title: My second post
Content: This is the content of the second post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
Id: 4e443d36e4a8497614dcc8d4
Title: My third post
Content: This is the content of the third post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
Id: 4e443d55e4a8497614dcc8d5
Title: My last post
Content: This is the content of the fourth post
comment 1 This is a sample comment
comment 2 This is another sample comment
comment 3 This is yet another sample comment
*/

Not that I want to sound like I’m bragging here, but this whole new script is a breeze to understand. As I said before, this time the aforementioned “find()” method is used for retrieving the entirety of the documents that exist in the collection, which are traversed and dumped to the screen via a simple “foreach” loop.

Of course, if you’re anything like me, it’s possible that you’re wondering if fetching some documents in a collection is all the functionality that MongoDB provides right out of the box. Well, not at all. In fact, the database permits you to perform a few more clever tasks in a straightforward fashion, such as counting, updating and removing documents too.

But, for now you’ll have to be patient, as these topics will be covered in detail in the coming installment. Meanwhile, feel free to have a look at the article’s closing remarks.   

Closing Thoughts

In this first part of the tutorial, I provided you with a quick introduction to what MongoDB is and how it can be put to work side by side with PHP. Even when the couple of examples that you saw before are indeed pretty simplistic, I think that they’re illustrative enough for showing how to deal with core concepts of the database, like collections and documents.

There’s no need to say that at this point I’m only scratching the surface when it comes to exploring all the good things that MongoDB brings to the table. But don’t feel concerned, though, as in the coming post I’ll be showing you how to count the number of documents present in a collection, as well as fetching them according to a specified condition.

As usual, stick with my recommendation and don’t miss the next part!


 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: