DatabaseMongoDB Delivers NoSQL Flexibility and Scalability to Developers

MongoDB Delivers NoSQL Flexibility and Scalability to Developers

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

One of the most popular open source NoSQL solutions is MongoDB, a solution which was released only last year yet is already seeing widespread adoption within enterprises such as github, The New York Times, and etsy. MongoDB stores data using a data structure which is “schemaless.”

The rise of MongoDB and the NoSQL database in general has promoted a radical new approach to data management, which is already replacing the use of relational databases in surprising places. NoSQL is a generic term for a database that does away with the notion of a formally defined schema and instead relies upon some other management approach such as a key-value store. These alternative approaches strive to provide developers with levels of flexibility, availability, and scalability not easily attainable using traditional relational databases.

Already in production use within mammoth online enterprises such as Amazon.com (Dynamo), Facebook (see Cassandra), and Google (see BigTable), the NoSQL movement is playing a major role in the operation of today’s Web, let alone the Web of tomorrow.

This article provides an introduction to MongoDB for developers, describing installation, the MongoDB shell, and using MongoDB with PHP.

Installing MongoDB

MongoDB supports all of the most common platforms, offering packages for Linux, Windows, and OS X. Obviously the installation process varies according to platform, so I’ll present only the process I used to install MongoDB on my Ubuntu 9.10 laptop. Begin by adding the following line to your /etc/apt/sources.list file:

deb http://downloads.mongodb.org/distros/ubuntu 9.10 10gen 

Next import the package’s public key into your system using the following command:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10 

Next update your package lists by running the following command:

%>sudo aptitude update 

Finally, install MongoDB by running the following command. Doing so will also configure MongoDB and start the MongoDB daemon:

%>sudo apt-get install mongodb-stable 

If you’re running another version of Ubuntu, see these instructions as you’ll need to point your sources.list file to a slightly different destination. If you’re running a different operating system, see the MongoDB documentation for further directions.

Using the MongoDB Shell

When installed, you can get acquainted with MongoDB by entering its interactive shell. Open a terminal window and execute the following command:

%>mongo MongoDB shell version: 1.4.3 url: test connecting to: 
test type "help" for help >

After logging into the shell, you can begin creating and managing data without even having to define a schema. Let’s create a database named library, which will store information about a summer reading list:

> use library switched to db library > db.books.save({title: 
'The Maltese Falcon'}) > db.books.find() { "_id" : ObjectId
("4c18fcf21469c2e4f93fe3b1"), "title" : "The Maltese Falcon" }

Now suppose you decide to also store the author names, and so enter your next book like this:

> db.books.save({title: 'Farewell to Arms', author: 'Ernest Hemingway'}) 

Run db.books.find() anew and you’ll see that two different book objects can reside in the same database, despite the first lacking an author:

> db.books.find() { "_id" : 
ObjectId("4c18fcf21469c2e4f93fe3b1"), "title" : "The Maltese Falcon" }
{ "_id" : ObjectId("4c18fe241469c2e4f93fe3b2"), "title" :
"Farewell to Arms", "author" : "Ernest Hemingway" }

Of course, you probably should add an author to the first book, and can do so using the following syntax:

> db.books.update({title: "The Maltese Shalcon"}, {title: 
"The Maltese Falcon", author: "Dashiell Hammett"}) >
db.books.find() { "_id" : ObjectId("4c18fe241469c2e4f93fe3b2"),
"title" : "Farewell to Arms", "author" : "Ernest Hemingway" }
{ "_id" : ObjectId("4c18fcf21469c2e4f93fe3b1"), "title" :
"The Maltese Falcon", "author" : "Dashiell Hammett" }

Another cool feature of MongoDB is the ability to find a record by passing any key/value pair to the find() method:

> db.books.find({author: "Ernest Hemingway"}) 
{ "_id" : ObjectId("4c18fe241469c2e4f93fe3b2"), "title" :
"Farewell to Arms", "author" : "Ernest Hemingway" }

Using MongoDB with PHP

MongoDB drivers are available for most of the popular programming languages, among them PHP, Python, and Ruby.

Configuring MongoDB for PHP is particularly easy, just install PHP’s MongoDB driver:

%>sudo pecl install mongodb

Then open your php.ini file and add the following line, restarting Apache after you save the file:

extension=mongo.so

When configured, you can create a script that queries the previously created library database:

<?php $m = new Mongo(); // Connect to a database $db = $m->library; 
// get the database named "foo"
// Retrieve the collection $books = $db->books;
// Find a book $book = $books->findOne(array('author' => 'Dashiell Hammett'));
// Output the title echo $book['title']; ?>

You can iterate over all books using the find() method and a looping mechanism:

// Retrieve the collection $books = $db->books->find(); while( $books->hasNext() ) 
{ $book = $books->getNext(); echo "{$book['title']}<br />"; }

Inserting new books is also quite easy, accomplished using the insert() method:

$books->insert(array('title' => 'The Sun Also Rises', 
'author' => 'Ernest Hemingway'));

For more information about using PHP with MongoDB, see the MongoDB documentation, which among other things provides links to quite a few community tools and plugins. Also, if you’re interested in using MongoDB in conjunction with Rails, be sure to check out the Developer.com article, A Rails Cloud Implementation Using MongoDB and Heroku.

Conclusion

NoSQL databases such as MongoDB are being adopted within enterprises large and small due to their flexibility and scalability, two traits which are music to most developers’ ears. Are you using MongoDB or a similar solution? If so, tell us about your experience in the comments!

About the Author

Jason Gilmore is the founder of EasyPHPWebsites.com. He also is the author of several popular books, including “Easy PHP Websites with the Zend Framework,” “Easy PayPal with PHP,” and “Beginning PHP and MySQL, Third Edition.”

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories