Hour 15. Working with MongoDB Data in PHP Applications


What You’ll Learn in This Hour:

Image Inserting new documents into a collection from PHP

Image Removing documents from a collection in PHP

Image Getting, manipulating, and saving a single document in a collection from PHP

Image Updating documents in a collection from PHP

Image Performing an upsert operation from PHP


In this hour, you return to the PHP MongoDB driver and explore how to implement it to add, manipulate, and remove documents from a collection in your PHP applications. You can change data in a collection using several methods. You can insert new documents, update existing documents using update or save, and remove old documents and apply an upsert (which first tries to update documents and, if none is found, inserts a new one).

The following sections cover the various methods on the PHP MongoCollection object that enable you to manipulate data in the collection. You see how to insert, delete, save, and update documents in a collection from your PHP application.

Adding Documents from PHP

An important task when interacting with MongoDB databases from PHP is inserting documents into collections. To insert a document, you need to first create an Array object that represents the document you want to store. Insert operations pass the Array object to the MongoDB sever as a BSON that you can insert into the collections.

When you have an Array version of your new document, you can store it in the MongoDB database using the insert() method on an instance of the MongoCollection object that is connected to the database. The following shows the syntax for the insert() method, where the doc parameter can be a single document object:

insert(doc)

For example, the following shows an example of inserting a single document and an array of documents into a collection:

$doc1 = array('name' => 'Fred');
$result = $myColl->insert($doc1);

To insert multiple documents into your collection, you can use the batchInsert() method on the MongoCollection object. The batchInsert() method accepts an array of Array objects representing documents in the collection. For example:

$doc2 = array('name' => 'George');
$doc3 = array('name' => 'Ron');
$result = $myColl->batchInsert([$doc2, $doc3]);

Notice that the insert() method returns a result object that contains information about the write operation.

Removing Documents from PHP

Sometimes you need to delete documents from your MongoDB collection from PHP, to keep space consumption down, improve performance, and keep things clean. The remove() method on MongoCollection objects makes it simple to delete documents from a collection. The syntax for the remove() method follows:

remove([query])

The query parameter is an Array object that identifies which document(s) you want to delete. The request matches the fields and values in the query with the fields and values of the object, and only those that match the query are updated. If no query is provided, all the documents in the collection are deleted.

For example, to delete all documents in the word_stats collection, you would use

$collection = $myDB->getCollection('word_stats');
$results = $collection->remove();

The following code deletes all words that start with a from the word_stats collection:

$collection = $myDB->getCollection('word_stats');
$query = array('first' => 'a');
collection->remove($query);

Saving Documents from PHP

A convenient method of updating objects in the database is to use the save() method on MongoCollection objects. The save method accepts an Array as a parameter and saves it to the database. If the document already exists in the database, it is updated with the new values. If the document does not already exist in the database, a new document is created.

The following shows the syntax of the save() method, where the doc parameter is the Array object representing the document to be saved to the collection:

save(doc)

Updating Documents from PHP

After objects have been inserted into a collection, you often need to update them from PHP as data changes. The update() method on the MongoCollection object enables you to update documents in a collection. The update method is versatile yet fairly easy to implement. The following shows the syntax for the update() method:

update(query, update, [options])

The query parameter is an Array object that identifies which document(s) you want to change. The request matches the properties and values in the query with the fields and values of the object, and only those that match the query are updated. The update parameter is an Array that specifies the changes to make to the documents that match the query. Hour 8, “Manipulating MongoDB Documents in a Collection,” describes the update operators used with this object.

The options parameter is an Array object that specifies the options for the update operation. You can set the upsert and multiple fields on an update() request. Setting the upsert field to true creates a new document in the collection if no objects match the query. Setting the multiple field to true applies the update to all documents that match the query; setting it to false updates only the first document.

For example, the following changes the category field value to old for items in the collection for which category currently is new. With upsert set to false, new documents are not created even if no documents have a category of new; with multiple set to true, all documents that match are updated:

$query = array('category' => 'New');
$update = array('$set' =>
    array('category' => 'Old'));
$options = array('upsert' => false, 'multiple' => true);
$myColl->update($query, $update, $options);

Upserting Documents from PHP

Another way to use the update() method on the MongoCollection object in PHP is with upsert operations. An upsert operation first tries to update documents in the collection. If no documents match the update query, the $set operator creates a new document and adds it to the collection. The following shows the syntax for the update() method:

update(query, update, [options])

The query parameter identifies which document(s) you want to change. The update parameter is an Array that specifies the changes to make to the documents that match the query. The options parameter specifies the write concern options, as well as upsert and multiple. For upsert operations the upsert option should be set to true and the multiple parameter should be set to false.

For example, the following performs an upsert on a document with name=myDoc. The $set operator defines the fields to create or update the document. With upsert set to true, if the document is not found, it is created; otherwise, it is updated:

$query = array('name' => 'myDoc');
$update = array('$set' =>
  array('name' => 'myDoc', 'number' => 5, 'score' => 10));
$options = array('w' => 1, 'j' => true, 'upsert' => true, 'multiple' => false);
$results = $collection->update($query, $update, $options);

Summary

In this hour, you used the PHP MongoDB driver to add, manipulate, and remove documents from a collection in your PHP applications. You used several different methods on the MongoCollection object to change data in a collection.

The insert() method adds new documents. The remove() method deletes documents. The save() method updates a single document.

The update() method can be used in multiple ways. You can have it update a single document or multiple documents. You can also apply the upsert option to insert new documents into the collection if none matches to be updated.

Q&A

Q. Will the PHP MongoDB driver objects throw exceptions when they encounter errors?

A. Yes. The PHP MongoDB driver includes several exception objects, such as MongoException and MongoCursorException, that can be thrown if errors occur inside the driver code.

Q. Is there a way to convert PHP Array objects to and from BSON objects?

A. Yes. The PHP MOngoDB driver provides the bson_encode(BSON) and bson_decode(array) methods to encode and decode BSON objects to and from arrays.

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. Which operation do you use from a PHP application to create a new document if one does not exist?

2. How do you limit the update() method to only a single document?

3. True or false: You can use the save() method on Collection objects only to save existing documents.

4. What type of parameter defines the fields to update in the update() method of the MongoCollection object?

Quiz Answers

1. You use the update() method on the MongoCollection object, with upsert set to true.

2. Set the multi parameter to false.

3. False. save() adds the document if it doesn’t exist.

4. It is an Array that contains MongoDB update operators as fields.

Exercises

1. Find a new word that you want to add to the word_stats collection in the example dataset. Write a new PHP application similar to PHPDocAdd.php file to add that word.

2. Create a new PHP application that uses the update() method to update all words with a first letter of e and add the category eWords to them.

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

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