Hour 13. Implementing MongoDB in PHP Applications


What You’ll Learn in This Hour:

Image Using the PHP MongoDB objects to access the MongoDB database

Image Implementing the PHP MongoDB driver in PHP applications

Image Connecting to the MongoDB database in PHP applications

Image Using methods to find and retrieve documents in PHP applications

Image Sorting documents in a cursor before retrieving them in PHP applications


This hour introduces you to implementing MongoDB in PHP applications. To be able to access and utilize MongoDB in a PHP application, you first need to implement the PHP MongoDB driver. The PHP MongoDB driver is a library that provides the necessary objects and functionality for accessing a MongoDB server from your PHP applications.

These objects are similar to the objects you have already been working with in the MongoDB shell. The examples in this hour and the following one rely on the fact that you already understand the structure of MongoDB objects and requests. If you have not already gone through Hours 59, you should go do so before continuing with this one.

The following sections describe the objects that you will be dealing with in PHP to access the MongoDB server, databases, collection, and documents. You also implement the PHP MongoDB driver and begin accessing documents in the example collection.

Understanding MongoDB Driver Objects in PHP

The PHP MongoDB driver provides several objects that enable you to connect to the MongoDB database and find and manipulate documents in collections. These objects represent the connection, database, collection cursor, and documents on the MongoDB server and provide the necessary functionality to integrate data from a MongoDB database into your PHP applications.

The following sections describe how each of these objects are created and used in PHP.

Understanding the PHP MongoClient Object

The PHP MongoClient object provides the functionality to connect to the MongoDB server and access databases. The first step you take in implementing MongoDB in your PHP applications is to create an instance of the MongoClient object. Then you can use the object to get the database, set the write concern, and perform other operations (see Table 13.1).

Image

TABLE 13.1 Methods Available on the MongoClient Object in PHP

To create an instance of the MongoClient object, you need to use new MongoClient() with the appropriate options. The most basic form connects on the localhost with a default port:

$mongo = new MongoClient("");

You can also use a connection string that uses this format:

mongodb://username:password@host:port/database?options

For example, to connect to the words database on host 1.1.1.1 on port 8888 with username test and password myPass, you would use the following:

$mongo = new MongoClient("mongodb://test:[email protected]:8888/words");

After you have created an instance of the MongoClient object, you can use the methods in Table 13.1 to get the database and set options.

Understanding the PHP MongoDB Object

The PHP MongoDB object provides the functionality to authenticate, access users, and access and manipulate collections. The simplest method of getting an instance of a MongoDB object is to access it directly by name on the MongoClient object. For example, the following gets a MongoDB object for the words database:

$mongo = new MongoClient("");
$db = $mongo->words;

You can also use the selectDB() method on the MongoClient object to get a Database object. This is especially useful if your database name does not work with the PHP -> syntax. For example:

$mongo = new MongoClient("");
$db = $mongo->selectDB("words");

After you have created an instance of the MongoDB object, you can use the object to access the database. Table 13.2 lists the more common methods available on the MongoDB object.

Image

TABLE 13.2 Methods Available on the MongoDB Object in PHP

Understanding the PHP MongoCollection Object

The PHP MongoCollection object provides the functionality to access and manipulate documents in a collection. The simplest method of getting an instance of a MongoCollection object is to access it directly by name on the MongoDB object. For example, the following gets a MongoCollection object for the word_stats collection on the words database:

$mongo = new MongoClient("");
$db = $mongo->words;
$collection = $db->word_stats;

You can also use the selectCollection() method on the MongoDB object to get a Database object. This is especially useful if your collection name does not work with the PHP -> syntax. For example:

$mongo = new MongoClient("");
$db = $mongo->selectDB("words");
$collection = $db->selectCollection("word_stats");

After you have created an instance of the MongoCollection object, you can use the object to access the collection. Table 13.3 lists the more common methods available on the MongoCollection object.

Image
Image

TABLE 13.3 Methods Available on the MongoCollection Object in PHP

Understanding the PHP MongoCursor Object

The PHP MongoCursor object represents a set of documents on the MongoDB server. Typically, a MongoCursor is returned when you query the collection using a find operation. Instead of returning the full set of document objects to the PHP application, a MongoCursor is returned, enabling you to access the documents in a controlled manner from PHP.

The MongoCursor object uses an index to iterate through documents on the server. The cursor pulls down documents from the server in batches. During iteration, when the index passes the end of the current batch, a new batch of documents is retrieved from the server.

The following code shows an example of getting an instance of the MongoCursor using a find operation:

$mongo = new MongoClient("");
$db = $mongo->words;
$collection = $db->word_stats;
$cursor = $collection->find();

After you have created an instance of the MongoCursor object, you can use the object to access documents in the collection. Table 13.4 lists the more common methods available on the MongoCursor object.

Image

TABLE 13.4 Methods Available on the MongoCursor Object in PHP

Understanding the PHP Array Objects Used As Parameters and Documents

As you saw in the MongoDB shell hours, most of the database, collection, and cursor operations accept objects as parameters. These objects define things such as query, sort, aggregation, and other operators. Documents are returned from the database as objects as well.

In the MongoDB shell, these are JavaScript objects. In PHP, however, objects that represent documents and request parameters are a specialized form of an associative Array object. When the server returns a document from a cursor or request, it is in an Array object, which has keys that match the fields in the document. For objects that you use as parameters to requests, you also use the Array object.

Array objects are built using the standard PHP syntax:

$myArr = array(key => value, ...);

Setting the Write Concern and Other Request Options

As you noticed in the previous sections, several methods enable you to specify an options Array object to set the write concern and other options. These options enable you to configure the write concern, timeout, and other options that best fit your application.

The following list describes some of the options you can set in the options Array object:

Image w: Sets the write concern value as 1 for acknowledged, 0 for unacknowledged, and majority for majority.

Image j: Set to true or false to enable or disable journal acknowledged.

Image wtimeout: Amount of time in milliseconds to wait for write concern acknowledgment.

Image timeout: Amount of time (in milliseconds) to wait for database response when using acknowledged requests.

Image upsert: Boolean. When true, an upsert is performed on update() requests.

Image multiple: Boolean. When true, multiple documents can be updated by update() requests.

As an example, the following shows building a basic options Array object in PHP:

$options = array('w' => 1, 'j' => true, 'wtimeout': 10000);

Finding Documents Using PHP

A common task in PHP applications is finding one or more documents that you need to use in your application. Finding documents in PHP is similar to finding them using the MongoDB shell. You can get one document or many and use queries to limit which documents are returned.

The following sections discuss using the PHP objects to find and retrieve documents from a MongoDB collection.

Getting the Documents from MongoDB Using PHP

The MongoCollection object provides the find() and findOne() methods, similar to what you saw in the MongoDB shell. These methods find a single document or multiple documents.

When you call findOne(), a single document is returned from the server as an Array object. You can then use the object in your application as needed. For example:

$doc = myColl->findOne();

The find() method on the MongoCollection object returns a MongoCursor object, which only represents the documents found and does not initially retrieve them. The MongoCursor object can be iterated in a few different ways.

You can use a while loop with the hasNext() method to determine whether you have reached the end of the cursor. For example:

$cursor = $myColl->find();
while($cursor->hasNext()){
  $doc = $cursor->getNext();
  print_r($doc);
}

You can also use the PHP foreach syntax to iterate through the Cursor object. For example, the following finds all documents and then uses foreach to display each one:

cursor = $collection->find();
foreach ($cursor as  $id => $doc){
  print_r($doc["word"]);
}

Finding Specific Documents from MongoDB Using PHP

More often than not, you will not want to retrieve all documents in a collection from the server. The find() and findOne() methods enable you to send a query object to the server that limits documents in the same way you saw with the MongoDB shell.

To build the query object, you can use the Array object described earlier. For fields in the object that require subobjects, you can create a sub Array object. For other types, such as integers, strings, and arrays, use the PHP equivalent.

For example, to create a query object that finds words with size=5, you would use

$query = array('size' => 5);
$myColl->find($query);

However, to create a query object that finds words with size>5, you would need to use

$query = array('size' =>
    array('$gt' => 5));
$myColl->find($query);

To create a query object that finds words with a first letter of x, y, or z, you would need to use a String array. For example:

$query = array('first' =>
    array('$in' => ["x", "y", "z"]));
$myColl->find($query);

You should be able to use these techniques to build any type of query object you need—not only for find operations, but for others that enable you to use a query object.

Counting Documents in PHP

When accessing document sets in MongoDB from PHP, you might want to just get a count first before deciding to retrieve a set of documents. Performing a count is much less intensive on the MongoDB server and client because the actual documents do not need to be transferred.

The count() method on the MongoCursor object enables you to get a simple count of documents that are represented. For example, the following code uses the find() method to get a MongoCursor object and then uses the count() method to get the number of items:

$cursor = $wordsColl->find();
$itemCount = $cursor->count();

The value of itemCount is the number of words that match the find() operation.

Sorting Result Sets in PHP

An important aspect of retrieving documents from a MongoDB database is the capability to get them in a sorted order. This is especially helpful if you are retrieving only a certain number, such as the top 10, or if you are paging the requests. The options object provides the sort option, which enables you to specify the sort order and direction of one or more fields in the document.

The sort() method on the MongoCursor object enables you to specify fields to sort the documents represented in the cursor and return them in that order. The sort() method accepts an Array that uses the field name as a property name and specifies the sort order as the value of 1 for ascending and -1 for descending.

For example, to sort on the name field in ascending order, you would use

$sorter = array('name' => 1);
$cursor = $myCollection->find();
$cursor->sort($sorter);

You can apply multiple fields to the object passed to the sort() method, and the documents will be sorted on those fields. You can also apply sort() multiple times on the same cursor to sort on different fields. For example, to sort on the name field descending first and then the value field ascending, you could use

$sorter = array('name' => 1, 'value' => -1);
$cursor = $myCollection->find();
$cursor->sort(sorter);

Or you could use

$sorter1 = array('name' => 1);
$sorter2 = array('value' => -1);
$cursor = $myCollection->find();
$cursor = $cursor->sort(sorter1)
$cursor->sort(sorter2);

Summary

In this hour, you looked at the objects the PHP MongoDB driver provides. These objects represent the connection, database, collection, cursor, and documents and provide functionality to access MongoDB from your PHP applications.

You also implemented the PHP MongoDB driver and created a basic PHP MongoDB application to connect to the database. Then you learned how to use the MongoCollection and MongoCursor objects to find and retrieve documents. Finally, you learned how to count and sort documents represented by the cursor before retrieving them.

Q&A

Q. Are there additional PHP objects not discussed in this hour?

A. Yes. This hour covers the major objects you need to know about, but the PHP MongoDB driver has a lot more supporting objects and functions. You can find the documentation at http://us2.php.net/mongo.

Q. Which versions of PHP support implementing MongoDB?

A. Currently, you can get a PHP MongoDB driver for PHP versions 5.2, 5.3, 5.4, and 5.5.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

1. How do you control which documents a find() operation returns?

2. How do you sort documents based on the name field in ascending order?

3. How do you get the value of fields in the MongoDB object?

4. True or false: The findOne() method returns a MongoCursor object.

Quiz Answers

1. Create an Array query object that defines a query filter.

2. Create an array('name' => 1) and pass it to the sort() method.

3. Use the get(fieldName) method.

4. False. It returns an Array object representing the document.

Exercises

1. Extend the PHPFindSort.php file to include a method that sorts documents first by size in descending order and then by last letter, also in descending order.

2. Extend the PHPFindSpecific.php file to find words that start with a and end with e.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.187.201