Home Web Development PHP and MongoDB Web Development Beginner's Guide

PHP and MongoDB Web Development Beginner's Guide

books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with MongoDB
About this book
With the rise of Web 2.0, the need for a highly scalable database, capable of storing diverse user-generated content is increasing. MongoDB, an open-source, non-relational database has stepped up to meet this demand and is being used in some of the most popular websites in the world. MongoDB is one of the NoSQL databases which is gaining popularity for developing PHP Web 2.0 applications.PHP and MongoDB Web Development Beginner’s Guide is a fast-paced, hands-on guide to get started with web application development using PHP and MongoDB. The book follows a “Code first, explain later” approach, using practical examples in PHP to demonstrate unique features of MongoDB. It does not overwhelm you with information (or starve you of it), but gives you enough to get a solid practical grasp on the concepts.The book starts by introducing the underlying concepts of MongoDB. Each chapter contains practical examples in PHP that teache specific features of the database.The book teaches you to build a blogging application, handle user sessions and authentication, and perform aggregation with MapReduce. You will learn unique MongoDB features and solve interesting problems like real-time analytics, location-aware web apps etc. You will be guided to use MongoDB alongside MySQL to build a diverse data back-end. With its concise coverage of concepts and numerous practical examples, PHP and MongoDB Web Development Beginner’s Guide is the right choice for the PHP developer to get started with learning MongoDB.
Publication date:
November 2011
Publisher
Packt
Pages
292
ISBN
9781849513623

 

Chapter 1. Getting Started with MongoDB

We are about to begin our journey in PHP and MongoDB web development. Since you picked up this book, I assume you have some background building web apps using PHP, and you are interested in learning to develop PHP applications with MongoDB as data backend. In case you have never heard of MongoDB before, it is an open source, document-oriented database that supports the concept of flexible schema. In this chapter, we will learn what MongoDB is, and what do we gain from using MongoDB instead of trusted old SQL databases. We will start by learning briefly about the NoSQL databases (a set of database technologies that are considered alternative to RDBM systems), the basics of MongoDB, and what distinguishes it from relational databases. Then we will move on to installing and running MongoDB and hooking it up with PHP.

To sum it up, in this chapter we will:

  • Learn about the NoSQL movement

  • Learn the basic concepts behind MongoDB

  • Learn how to download, install, and run MongoDB on a computer

  • Learn to use the mongo Interactive Shell

  • Learn how to make PHP and MongoDB talk to each other

So let's get on with it...

The NoSQL movement

You probably have heard about NoSQL before. You may have seen it in the RSS feed headlines of your favorite tech blogs, or you overheard a conversation between developers in your favorite restaurant during lunch. NoSQL (elaborated "Not only SQL"), is a data storage technology. It is a term used to collectively identify a number of database systems, which are fundamentally different from relational databases. NoSQL databases are increasingly being used in web 2.0 applications, social networking sites where the data is mostly user generated. Because of their diverse nature, it is difficult to map user-generated content to a relational data model, the schema has to be kept as flexible as possible to reflect the changes in the content. As the popularity of such a website grows, so does the amount of data and the read-write operations on the data. With a relational database system, dealing with these problems is very hard. The developers of the application and administrators of the database have to deal with the added complexity of scaling the database operations, while keeping its performance optimum. This is why popular websites—Facebook, Twitter to name a few—have adopted NoSQL databases to store part or all of their data. These database systems have been developed (in many cases built from scratch by developers of the web applications in question!) with the goal of addressing such problems, and therefore are more suitable for such use cases. They are open source, freely available on the Internet, and their use is increasingly gaining momentum in consumer and enterprise applications.

Types of NoSQL databases

The NoSQL databases currently being used can be grouped into four broad categories:

  • Key-value data stores: Data is stored as key-value pairs. Values are retrieved by keys. Redis, Dynomite, and Voldemort are examples of such databases.

  • Column-based databases: These databases organize the data in tables, similar to an RDBMS, however, they store the content by columns instead of rows. They are good for data warehousing applications. Examples of column-based databases are Hbase, Cassandra, Hypertable, and so on.

  • Document-based databases: Data is stored and organized as a collection of documents. The documents are flexible; each document can have any number of fields. Apache CouchDB and MongoDB are prominent document databases.

  • Graph-based data-stores: These databases apply the computer science graph theory for storing and retrieving data. They focus on interconnectivity of different parts of data. Units of data are visualized as nodes and relationships among them are defined by edges connecting the nodes. Neo4j is an example of such a database.

 

The NoSQL movement


You probably have heard about NoSQL before. You may have seen it in the RSS feed headlines of your favorite tech blogs, or you overheard a conversation between developers in your favorite restaurant during lunch. NoSQL (elaborated "Not only SQL"), is a data storage technology. It is a term used to collectively identify a number of database systems, which are fundamentally different from relational databases. NoSQL databases are increasingly being used in web 2.0 applications, social networking sites where the data is mostly user generated. Because of their diverse nature, it is difficult to map user-generated content to a relational data model, the schema has to be kept as flexible as possible to reflect the changes in the content. As the popularity of such a website grows, so does the amount of data and the read-write operations on the data. With a relational database system, dealing with these problems is very hard. The developers of the application and administrators of the database have to deal with the added complexity of scaling the database operations, while keeping its performance optimum. This is why popular websites—Facebook, Twitter to name a few—have adopted NoSQL databases to store part or all of their data. These database systems have been developed (in many cases built from scratch by developers of the web applications in question!) with the goal of addressing such problems, and therefore are more suitable for such use cases. They are open source, freely available on the Internet, and their use is increasingly gaining momentum in consumer and enterprise applications.

Types of NoSQL databases

The NoSQL databases currently being used can be grouped into four broad categories:

  • Key-value data stores: Data is stored as key-value pairs. Values are retrieved by keys. Redis, Dynomite, and Voldemort are examples of such databases.

  • Column-based databases: These databases organize the data in tables, similar to an RDBMS, however, they store the content by columns instead of rows. They are good for data warehousing applications. Examples of column-based databases are Hbase, Cassandra, Hypertable, and so on.

  • Document-based databases: Data is stored and organized as a collection of documents. The documents are flexible; each document can have any number of fields. Apache CouchDB and MongoDB are prominent document databases.

  • Graph-based data-stores: These databases apply the computer science graph theory for storing and retrieving data. They focus on interconnectivity of different parts of data. Units of data are visualized as nodes and relationships among them are defined by edges connecting the nodes. Neo4j is an example of such a database.

 

MongoDB A document-based NoSQL database


MongoDB falls into the group of document-oriented NoSQL databases. It is developed and maintained by 10gen (http://www.10gen.com). It is an open source database, written in the programming language C. The source code is licensed under AGPL and freely available at GitHub, anyone can download it from the repo https://github.com/mongodb/mongo and customize it to suit his/her needs. It is increasingly being used as a data storage layer in different kinds of applications, both web-based and nonweb-based.

Why MongoDB?

Features that make learning and using MongoDB a win, include:

  • Easy to learn, at least easier than learning other NoSQL systems, if I dare say. Column-oriented or graph-based databases introduce radical ideas that many developers struggle to grasp. However, there is a lot of similarity in the basic concepts of MongoDB and a relational database. Developers coming from an RDBMS background, find little trouble adapting to MongoDB.

  • It implements the idea of flexible schema. You don't have to define the structure of the data before you start storing it, which makes it very suitable for storing non-structured data.

  • It is highly scalable. It comes with great features to help keep performance optimum, while the size and traffic of data grows, with little or no change in the application layer.

It is free, it can be downloaded and used without charge. It has excellent documentation and an active and co-operative online community who participate in mailing lists, forums, and IRC chat rooms.

Who is using MongoDB?

Let's take a look at some real world use cases of MongoDB:

  • Craigslist: Craigslist is the world's most popular website for featuring free classified advertisements. It uses MongoDB to archive billions of records. They had been using a MySQL based solution for achieving that. Replacing them with MongoDB has allowed them to add schema changes without delay, and scale much more easily.

  • Foursquare: Foursquare is a popular location-based social networking application. It stores the geographical location of interesting venues (restaurants, cafes, and so on) and records when users visit these venues. It uses MongoDB for storing venue and user information.

  • CERN: The renowned particle physics laboratory based in Geneva, uses MongoDB as an aggregation cache for its Large Hadron Collider experiment. The results for expensive aggregation queries, performed on massive amounts of data, are stored in MongoDB for future use.

MongoDB concepts—Databases, collections, and documents

A MongoDB server hosts a number of databases. The databases act as containers of data and they are independent of each other. A MongoDB database contains one or more collections. For example, a database for a blogging application named myblogsite may typically have the collections articles, authors, comments, categories, and so on.

A collection is a set of documents. It is logically analogous to the concept of a table in a relational database. But unlike tables, you don't have to define the structure of the data that is going to be stored in the collection beforehand.

A document stored in a collection is a unit of data. A document contains a set of fields or key-value pairs. The keys are strings, the values can be of various types: strings, integers, floats, timestamps, and so on. You can even store a document as the value of a field in another document.

Anatomy of document

Let's take a closer look at a MongoDB document. The following is an example of a document that stores certain information about a user in a web application:

{
_id : ObjectId("4db31fa0ba3aba54146d851a")
username : "joegunchy"
email : "joe@mysite.org"
age : 26
is_admin : true
created : "Sun Apr 24 2011 01:52:58 GMT+0700 (BDST)"
}

The previous document has six fields. If you have some JavaScript experience, you would recognize the structure as JSON or JavaScript Object Notation. The value for the first field, _id, is autogenerated. MongoDB automatically generates an ObjectId for each document you create in a collection and assigns it as _id for that document. This is also unique; that means no two documents in the same collection will have the same values for ID, just like a primary key of a table in a relational database. The next two fields, username and email are strings, age is an integer, and is_admin is boolean. Finally, created is a JavaScript DateTime object, represented as a string.

BSON—The data exchange format for MongoDB

We have already seen that the structure of a document imitates a JSON object. When you store this document in the database, it is serialized into a special binary encoded format, known as BSON, short for binary JSON. BSON is the default data exchange format for MongoDB. The key advantage of BSON is that it is more efficient than conventional formats such as XML and JSON, both in terms of memory consumption and processing time. Also, BSON supports all the data types supported by JSON (string, integer, double, Boolean, array, object, null) plus some special data types such as regular expression, object ID, date, binary data, and code. Programming languages such as PHP, Python, Java, and so on have libraries that manage conversion of language-specific data structures (for example, the associative array in PHP) to and from BSON. This enables the languages to easily communicate with MongoDB and manipulate the data in it.

Note

If you are interested to learn more about BSON format, you may try visiting http://bsonspec.org/.

Similarity with relational databases

Developers with a background on working with relational database systems will quickly recognize the similarities between the logical abstractions of the relational data model and the Mongo data model. The next figure compares components of a relational data model with those of the Mongo data model:

The next figure shows how a single row of a hypothetical table named users is mapped into a document in a collection:

Also just like columns of a RDBMS table, fields of a collection can be indexed, although implementations of indexing are different.

So much for the similarities: now let's talk briefly about the differences. The key thing that distinguishes MongoDB from a relational model is the absence of relationship constraints. There are no foreign keys in a collection and as a result there are no JOIN queries. Constraint management is typically handled in the application layer. Also, because of its flexible schema property, there is no expensive ALTER TABLE statement in MongoDB.

 

Downloading, installing, and running MongoDB


We are done with the theoretical part, at least for now. It is time for us to download, install, and start playing with MongoDB on the computer.

System requirements

MongoDB supports a wide variety of platforms. It can run on Windows (XP, Vista, and 7), various flavors of Linux (Debian/Ubuntu, Fedora, CentOS, and so on), and OS X running on Intel-based Macs. In this section, we are going to see step-by-step instructions for having a MongoDB system up and running in a computer, running on Windows, Linux, or OS X.

 

Time for action - downloading and running MongoDB on Windows


We are going to learn how to download, install, and run MongoDB on a computer running on Windows:

  1. 1. Head on over to the downloads page on the MongoDB official website, http://www.mongodb.org/downloads.

  2. 2. Click on the download link for the latest stable release under Windows 32-bit. This will start downloading a ZIP archive:

  3. 3. Once the download is finished, move the ZIP archive to the C:\ drive and extract it. Rename the extracted folder (mongodb-win32-i386-x.y.z where x.y.z is the version number) to mongodb.

  4. 4. Create the folder C:\data\db. Open a CMD prompt window, and enter the following commands:

    C:\> cd \mongodb\bin
    C:\mongodb\bin> mongod
    
  5. 5. Open another CMD prompt window and enter the following commands:

    C:\> cd \mongodb\bin
    C:\mongodb\bin> mongo
    
  6. 6. Type show dbs into the shell and hit Enter.

What just happened?

In steps 1 to 3, we downloaded and extracted a ZIP archive that contains binary files for running MongoDB on Windows, moved and extracted it under the C:\ drive, and renamed the folder to mongodb for convenience. In step 4, we created the data directory (C:\data\db). This is the location where MongoDB will store its data files. In step 5, we execute the C:\mongodb\bin\mongod.exe program in the CMD prompt to launch the MongoDB server; this is the server that hosts multiple databases (you can also do this by double-clicking on the file in Windows Explorer). In step 6, after the server program is booted up, we invoke the C:\mongodb\bin\mongo.exe program to start the mongo interactive shell, which is a command-line interface to the MongoDB server:

C:\mongodb\bin\mongo
MongoDB shell version: 1.8.1
connection to test
type "help" for help
>

Once the shell has started, we issue the command show dbs to list all the pre-loaded databases in the server:

>show dbs
admin (empty)
local (empty)
>

Installing the 64-bit version

The documentation at the MongoDB website recommends that you run the 64-bit version of the system. This is because the 32-bit version cannot store more than 2 gigabytes of data. If you think it is likely that the data in your database will exceed the 2 GB limit, then you should obviously download and install the 64-bit version instead. You will also need an operating system that supports running applications in the 64-bit mode. For the purpose of the practical examples shown in this book, we are just fine with the 32-bit version, you should not worry about that too much.

 

Time for action - downloading and running MongoDB on Linux


Now, we are going to learn how to download and run the MongoDB server on a Linux box:

  1. 1. Fire up the terminal program. Type in the following command and hit Enter

    wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.3.tgz > mongo.tgz
    
  2. 2. Extract the downloaded archive by using the following command:

    tar xzf mongo.tgz
    
  3. 3. Rename the extracted directory by using the following command:

    mv mongodb-linux-i686-1.8.3 mongodb
    
  4. 4. Create the data directory /data/db by using the following command:

    sudo mkdir p /data/db
    sudo chown `id -u` /data/db
    
  5. 5. Startup the server by running the following command:

    ./mongodb/bin/mongod
    
  6. 6. Open another tab in the terminal and run the next command:

    ./mongodb/bin/mongo
    
  7. 7. Type show dbs into the shell and hit Enter.

What just happened?

In step 1, we downloaded the latest stable release of MongoDB 32-bit version for Linux using the wget program, and stored it as a GZIP tarball named mongo.tgz on your machine.

Note

At the time of this writing, the latest production release for MongoDB is 1.8.3. So when you try this, if a newer production release is available, you should download that version instead.

In steps 2 and 3, we extracted the tarball and renamed the extracted directory to mongodb for convenience. In step 4, we created the data directory /data/db for MongoDB, and gave it permission to read from and write to that directory. In step 5, we startup the MongoDB server by executing the mongodb/bin/mongod script.

In step 6, after we have successfully launched the server, we start the mongo interactive shell:

$./mongodb/bin/mongo
MongoDB shell version: 1.8.1
url: test
connection to test
type "help" for help
>

Once the shell has started, we issue the command show dbs to list all the pre-loaded databases in the server:

>show dbs
local (empty)
admin (empty)
>

The databases listed here are special databases pre-built within the server. They are used for administration and authentication purposes. We do not need to concern ourselves with them right now.

Note

Installing MongoDB using package managers

You can use the package manager of your Linux distribution (apt for Debian/Ubuntu, yum for Fedora/CentOS) to install MongoDB. To get distro-specific instructions, Ubuntu/Debian users should visit http://www.mongodb.org/display/DOCS/Ubuntu+and+Debian+packages. Users of CentOS and Fedora should visit http://www.mongodb.org/display/DOCS/CentOS+and+Fedora+Packages. The advantage of using a package manager, other than being able to install with fewer commands, is that you can launch the Mongo server and the client just by typing mongod and mongo respectively in the shell.

Installing MongoDB on OS X

The instructions for installing MongoDB on an OS X powered Mac machine are the same as those for Linux. You have to download the OS X specific binaries for Mongo (available at http://www.mongodb.org/downloads), and follow the same steps to execute them.

Alternatively, if you have package managers installed on your OS X (Homebrew or MacPorts), you can use them to install MongoDB.

To install MongoDB with HomeBrew use the following command:

$ brew update
$ brew install mongodb

To use MacPorts to install MongoDB use the following command:

$ sudo port install mongodb

Configuring MongoDB

When we launched the mongod program, it booted up with some default configuration settings, such as the path to the data directory (C:\data\db on Windows or /data/db on Unix). In real world deployments, we want to be able to specify these settings ourselves. There are two ways to achieve that. We can either modify them by supplying command-line parameters to the mongod program at invocation, or by using file-based configurations.

Command-line parameters

We can override the default MongoDB settings by passing command-line parameters to the mongod program. For example, the next command tells MongoDB to use C:\mongodb_data as data directory by sending it as a --dbpath argument:

C:\>mongodb\bin\mongod --dbpath C:\mongodb_data

The following table lists some useful command-line parameters and their functions:

Parameter

What it does

--dbpath

Path to the directory for storing data files.

--bind_ip

IP address that the mongod server will listen on, default is 127.0.0.1.

--port

Port address that mongod will listen on, default is 27017.

--logpath

Full file path to the log file where the MongoDB messages will be written. By default all messages are written to standard output.

--logappend

Setting this option to true appends the messages at the end of the log file. Setting it to false overwrites the log.

We can see the full list of command-line options by running mongod with the--help option:

C:\>mongodb\bin\mongod -help

File-based configuration

An alternative to sending all those command-line parameters to mongod manually is to put the required configuration settings in a file and then pass the path of the file as a--config option. For example, consider the following sample configuration file:

dbpath = D:\mongodb_data
logpath = D:\mongodb.log
logappend = true

We store this file to a location, say C:\mongodb.conf. Now, to start MongoDB with the these settings, we have to enter the next command in the CMD prompt:

C:\>mongodb\bin\mongod --config C:\mongodb.conf

mongod will be loaded with these configuration settings. Note that file-based parameters are the same as those for command-line options.

Note

If you are on a Linux machine, and you have installed Mongo using a package manager, such a configuration file may already exist in your system, typically at the location /etc/mongo.conf. You can modify that file to boot Mongo server with the configuration of your choice.

Have a go hero configure MongoDB to run with non-default settings

Start MongoDB with the following settings, using a file-based configuration:

  • Default data directory at /usr/bin/mongo.

  • Default port address at 8888.

  • Messages will be logged at /var/logs/mongodb.log. The log file should be overwritten over time.

Stopping MongoDB

There are several ways you can shutdown a running MongoDB server.

Hitting Control + C

In the terminal window (or CMD prompt window in case you are on Windows) running the mongod process, hit Ctrl + C. This will signal the server to do a clean shutdown, flush, and close its data files.

From the mongo shell

From the mongo interactive shell, you can issue a shutdownServer() command, causing mongod to terminate:

>use admin
switched to db admin
>db.shutdownServer()

Sending INT or TERM signal in UNIX

In Linux/OS X, you can send a kill -2 <PID> signal to the process running mongod, which will cause the server to shutdown cleanly. You can get the PID by running the following command:

ps aef | grep mongod
 

Creating databases, collections, and documents


Now that you have MongoDB up and running on your computer, it is time for us to create some databases, collections, and documents.

 

Time for action - creating databases, collections, and documents


The next example will demonstrate how to create a database, and insert a document in a collection using the mongo shell program:

  1. 1. In the mongo shell, enter the following command:

    >use myfirstdb
    
  2. 2. When the prompt returns, enter the following commands to create documents in a collection named movies:

    >db.movies.insert({name:"Source Code", genre:"sci-fi", year:2011})
    >db.movies.insert({name:"The Dark Knight", genre:"action", year:2008})
    >db.movies.insert({name:"Megamind", genre:"animation", year:2010})
    >db.movies.insert({name:"Paranormal Activity", genre:"horror", year:2009})
    >db.movies.insert({name:"Hangover", genre:"comedy", year:2010})
    
  3. 3. The following command returns all documents from the movies collection:

    >db.movies.find()
    

What just happened?

In step 1, we applied the use myfirstdb command to switch to a new database namespace. Any collection/document we create now is going to be stored under this database. Next we create a collection named movies and insert some documents in it:

>db.movies.insert({name:"Source Code",genre:"sci-fi",year:2011})

The db part of the command always refers to the current database, which is "myfirstdb" in this case. The next part is the name of the collection (movies), if it does not already exist in the database, it gets created automatically when you invoke the insert() method on it. The argument to insert is a JSON object, a set of key-value pairs. After invoking the first insert, the database myfirstdb comes into physical existence. You can look into the data directory at this point, where you will find the files myfirstdb.0, myfirstdb.1, and so on that are storing the data for this database.

The find() command, invoked on the collection, returns all the documents in it:

>db.movies.find()
{ "_id" : ObjectId("4db439153ec7b6fd1c9093ec"), "name" : "Source Code", "genre" : "sci-fi", "year" : 2011 }
{ "_id" : ObjectId("4db439df3ec7b6fd1c9093ed"), "name" : "The Dark Knight", "genre" : "action", "year" : 2008 }
{ "_id" : ObjectId("4db439f33ec7b6fd1c9093ee"), "name" : "Megamind", "genre" : "animation", "year" : 2010 }
{ "_id" : ObjectId("4db439f33ec7b6fd1c9093ef"), "name" : "Paranormal Activity", "genre" : "horror", "year" : 2009 }
{ "_id" : ObjectId("4db439f43ec7b6fd1c9093f0"), "name" : "Hangover", "genre" : "comedy", "year" : 2010 }

Pop Quiz - configuring MongoDB

  1. 1. What is the default port address of MongoDB?

    a. 27107

    b. 27017

    c. 27170

  2. 2. How does a new database get created in MongoDB?

    a. By the command create database <databasename>

    b. By the command use <databasename>

    c. By doing use <databasename> first and then doing db.<collectionname>.insert(<jsondocument>)

 

Installing the PHP driver for MongoDB


To make PHP talk to the MongoDB server, we are going to need the PHP-MongoDB driver. It is a PHP extension library that manages connection to the MongoDB server and enables you to perform all kinds of operations on a database through PHP. Since you are a PHP programmer, I am going to assume you already have a functional PHP environment installed on your machine, running on top of an Apache web server. The driver officially supports PHP versions 5.1, 5.2, and 5.3. So if you are using an older version of PHP, I suggest you upgrade it.

 

Time for action - installing PHP driver for MongoDB on Windows


Let's try installing the driver on a Windows machine running PHP 5.2 on Apache:

  1. 1. Download the ZIP archive http://downloads.mongodb.org/mongo-latest-php5.2vc6ts.zip on your machine and extract it.

  2. 2. Copy the php_mongo.dll file from the extracted folder to the PHP extension directory; this is usually the folder name ext inside your PHP installation.

  3. 3. Open the php.ini file inside your PHP installation and add the following line:

    extension=php_mongo.dll
    
  4. 4. Save the file and close it. Restart the Apache web server.

  5. 5. Open up your text editor and add the following code to a new file:

    <?php
    phpinfo();
    
  6. 6. Save the file as phpinfo.php inside the DocumentRoot of the Apache web server (the htdocs folder).

  7. 7. Execute the phpinfo.php script in your browser (http://localhost/phpinfo.php). Scroll down to find the section mongo to see all the MongoDB driver-specific information.

Congratulations! You have successfully installed the PHP driver for MongoDB.

What just happened?

In step 1, we download the ZIP file containing the DLL file php_mongo.dll for the PHP-MongoDB driver for PHP 5.2 (for the PHP 5.3 specific version, download http://downloads.mongodb.org/mongo-latest-php5.3vc6ts.zip instead). In step 2, we copy the php_mongo.dll file to the PHP extensions directory. If the installation directory of PHP on your machine is C:\php, the extension directory should be C:\php\ext. Then we edit the php.ini file (located under C:\php as well) to add the line extension=php_mongo.dll to it and restart Apache for the changes to take effect. Next we create and execute a one-line PHP script to invoke the phpinfo() method. If we are able to see the MongoDB driver specific information in the phpinfo() output, listed under section mongo, this means the driver was installed without a glitch.

Note

If you are running PHP on IIS, you should download the thread-safe VC9 version of the driver instead. Get it from the URL http://downloads.mongodb.org/mongo-latest-php5.3vc9ts.zip.

Installing the PHP-MongoDB driver on Unix

In a Unix-based system, the PHP driver for MongoDB can be installed using the pecl (PECL - PHP Extension Community Islam) program. You need to have it installed on your machine, which can be done by using the following command:

sudo pecl install mongo

When the installation is finished, edit the php.ini file (usually found at /etc/php.ini) to add the line:

extension=mongo.so

and then restart Apache.

In case you don't have pecl installed on your machine, you can download the driver source code from GitHub, build it, and install it manually:

$ tar zxvf mongodb-mongdb-php-driver-<commit_id>.tar.gz
$ cd mongodb-mongodb-php-driver-<commit_id>
$ phpize
$ ./configure
$ sudo make install

Check out the Mongo driver installation page http://www.php.net/manual/en/mongo.installation.php on the PHP official website to get operating system specific detailed information.

 

Connecting to the MongoDB server from PHP


In this section, we will learn how to use the API provided by the PHP-MongoDB driver to create a connection to the Mongo server from a PHP script.

Creating a PHP-Mongo connection

Let's write a very simple PHP program that creates a connection to the MongoDB server and shows all the available databases on that server.

 

Time for action - creating a connection to the MongoDB server from PHP


  1. 1. Open up your text editor and add the following code in a new file:

    <?php
    try{
    $mongo = new Mongo(); //create a connection to MongoDB
    $databases = $mongo->listDBs(); //List all databases
    echo '<pre>';
    print_r($databases);
    $mongo->close();
    } catch(MongoConnectionException $e) {
    //handle connection error
    die($e->getMessage());
    }
    
  2. 2. Save the file as test_connection.php under the DocumentRoot of your web server.

  3. 3. Open up your browser, and execute the script by going to the location http://localhost/test_connection.php:

What just happened?

We just wrote a simple PHP program to test if the PHP-MongoDB driver we installed works correctly. The program does two simple things. First, it creates a connection to the Mongo server, then it lists all the databases in the server.

Let's examine the code. We created a connection from PHP to MongoDB by instantiating a Mongo object:

try{
$mongo = new Mongo();
……………………………………………………
} catch(MongoConnectionException $e) {
die($e->getMessage());
}

We instantiated the object within a try/catch block to handle the exception named MongoConnectionException in case PHP fails to connect. Once the connection was made, we invoked the listDBs() method on the Mongo object. It returned an associative array, containing three fields. The first field—databases—is an array of associative arrays, each one corresponding to a database in the server, giving us the name of the database, its size in bytes, and a flag specifying if the database is empty or not.

Array
(
[databases] => Array
(
[0] => Array
(
[name] => myfirstdb
[sizeOnDisk] => 67108864
[empty] =>
)
[1] => Array
(
[name] => adming
[sizeOnDisk] => 1
[empty] => 1
)
)
[totalSize] => 67108864
[ok] => 1
)

The totalSize field corresponds to the total size of data in the server (in bytes) and the ok flag specifies if the method ran successfully. Finally, we closed the connection by invoking the close() method on the Mongo object.

Configuring the PHP-MongoDB connection

When no parameter is passed to the constructor of the Mongo class, it connects to the Mongo server running on localhost, on port 27107 (or whatever value is specified for mongo.default_host and mongo.default_port in php.ini). If we want to connect to a server running on a different host and/or port, we can pass the connection string (mongodb://<hostname>:<port_number>) as the $server parameter to the Mongo constructor. For example, to connect to a Mongo server listening on port 8888, we will type the following command:

$mongo = new Mongo($server="mongodb://localhost:8888");

Specifying timeout for the connection attempt

We can specify for how long (in milliseconds) the driver should attempt to connect to the MongoDB server:

try {
$mongo = new Mongo($options=array('timeout'=> 100))
} catch(MongoConnectionException $e) {
die("Failed to connect to database ".$e->getMessage());
}

We supplied an array {'timeout' => 100} as the $option argument to the Mongo constructor. In case PHP fails to connect within 100 milliseconds, it will throw an exception named MongoConnectionException.

Have a go hero connect to a MongoDB server on a networked computer

Suppose your computer is connected to a local area network. There is another computer in the network, running on the IP address 192.168.1.101. It is hosting a MongoDB server that is listening on port 8000. Write a PHP script that connects to that MongoDB server, in under one second, and lists all the databases hosted there.

 

Summary


We covered a lot of things in this chapter.

Specifically, we covered:

  • What the NoSQL movement is

  • What MongoDB is, what is it good for, and who is using it

  • The MongoDB data model (databases, collections, and documents)

  • How to install and run MongoDB on a computer

  • How to create databases, collections, and documents using the mongo interactive shell.

  • How to install the MongoDB-PHP driver on a computer

  • How to create a connection to MongoDB from PHP

We also discussed how to configure the MongoDB server using command-line parameters or configuration files.

By now you should have a PHP-MongoDB development environment up and running on your system. In the next chapter, we will learn to create a simple web application using MongoDB as data backend.

PHP and MongoDB Web Development Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now