Using MongoDB with PHP: Using Documents

In the following subsections we shall discuss adding, querying, updating, and deleting a document in MongoDB server using the PHP MongoDB Driver.

1. Adding a Document

The MongoCollection::insert method is used to add a single document to MongoDB. The insert() method takes parameters.

MongoCollection::insert ( array|object $document [, array $options = array() ] )

The first parameter is an array or an object and if the parameter does not provide an _id key a new MongoId instance is created and assigned to it. The insert method supports the following options listed in Table 3-5.

  1. Create a PHP script addDocument.php in the C:\php directory. In a try-catch statement create a MongoClient instance, which represents a connection, and create a MongoCollection instance in local database for catalog collection.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Create an array for a document to add.

$doc = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle

Magazine’, “publisher” => ‘Oracle Publishing’, “edition” => ‘November December

2013′,”title” => ‘Engineering as a Service’,”author” => ‘David A. Kelly’)

);

  1. Add the document to the MongoDB collection using the insert() method.

$status=$collection->insert($doc);

var_dump($status);

  1. Add catch blocks for MongoConnectionException and MongoCursorException.
  2. Similarly add another document to the collection. The addDocument.php script is listed below.

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$doc = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle

Magazine’, “publisher” => ‘Oracle Publishing’, “edition” => ‘November December

2013′,”title” => ‘Engineering as a Service’,”author” => ‘David A. Kelly’)

);

$status=$collection->insert($doc);

var_dump($status);

print ‘<br/>’;

$doc = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle

Magazine’, “publisher” => ‘Oracle Publishing’, “edition” => ‘November December

2013′,”title” => ‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’)

);

$status=$collection->insert($doc);

var_dump($status);

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Run the PHP script in the browser with the URL http://localhost:8000/php. The output is shown in Figure 3-11. As indicated by the status message array returned by the insert() method the err key is NULL, which implies no error and the errmsg is also NULL. And the ok key is 1, which implies all database operations completed successfully. The n key indicates the number of documents affected, which is 0 for an insert. The n for an update, upsert, or remove would be a positive number if document/s have been updated, upserted, or removed.

As we did not provide a _id key for the documents added, a unique MongoId is created automatically for the documents added. The _id key or MongoId must be unique. Next, we shall demonstrate that the _id or MongoId must be unique.

Using a try-catch statement create and add a document using the insert() method. Invoke the insert method on the same document twice.

$status=$collection->insert($doc);

$status=$collection->insert($doc);

The addDocumentException.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$doc = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Engineering as a Service’,”author” => ‘David A. Kelly’)

);

$status=$collection->insert($doc);

var_dump($status);

print ‘<br/>’;

$status=$collection->insert($doc);

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

When the addDocumentException.php script is run in a browser (URL http://localhost:8000/ addDocumentException.php) the MongoCursorException exception is thrown as the same document is being tried to be added twice. The exception is caught and an error message is output as shown in Figure 3-12.

2. Adding Multiple Documents

In the preceding section we added two documents using two separate invocations of the insert() method. The insert() method invocations may also be made using a while, do-while, or for loop.

  1. Create a PHP script addMultipleDocuments.php in the document root directory C:\php. In a try-catch statement create an instance of MongoCollection for a collection as before.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. In a for loop add documents to the collection using the variable $i from the for loop initializer in the catalogId field for the documents.

for ($i = 1; $i <= 5; $i++)

{

$status=$collection->insert(array(“catalogId” =>’catalog’.$i, “journal” =>

‘Oracle Magazine’, “publisher” => ‘Oracle Publishing’, “edition” => ‘November

December 2013′));

var_dump($status);

print ‘<br/>’;

}

The addMultipleDocuments.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

for ($i = 1; $i <= 5; $i++)

{

$status=$collection->insert(array(“catalogId” =>’catalog’.$i, “journal” =>

‘Oracle Magazine’, “publisher” => ‘Oracle Publishing’, “edition” =>

‘November December 2013’)); var_dump($status); print ‘<br/>’;

}

}catch (MongoConnectionException $e)

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

3. Run the addMultipleDocuments.php script in a browser with URL

http://localhost:8000/addMultipleDocuments.php to add multiple documents to the MongoDB collection. A status message gets output for each document added as shown in Figure 3-13.

3. Adding a Batch of Documents

The MongoCollection::batchInsert() method may be used to add a batch of documents to a collection. The method syntax is the same as the insert method.

MongoCollection::batchInsert ( array $document [, array $options = array() ] )

The difference from the insert() method is that the first parameter a is of type array of arrays or objects instead of array or object in the insert method. The batchInsert() method returns an associative array instead of the array or boolean for the insert method. The method supports one additional option, the continueOnError option, which defaults to false. If set to true the bulk insert fails if insert for one of the documents fails. Each of the documents in the array of documents to be added in a batch must have a unique _id.

  1. Create a PHP script addDocumentBatch.php in the C:\php directory. Create a MongoCollection instance as before.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Create an array to which the document arrays are to be added.

$batch=array();

  1. Create a document array and add the array to the $batch array.

$doc1 = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,

“title” => ‘Engineering as a Service’,”author” => ‘David A. Kelly’)

);

$batch[]=$doc1;

  1. Similarly add another document to the batch array. The $doc2 is declared in the addDocumentBatch.php script listing.

$batch[]=$doc2;

  1. Invoke the batchInsert method with the $batch array as arg.

$status=$collection->batchInsert($batch);

var_dump($status);

  1. As the _id fields for the documents to be added are not provided the MongoId instances are added automatically. Subsequently the _id field values added may be output in a foreach loop.

foreach ($batch as $doc) {

print ‘Document _id: ‘;

echo $doc[‘_id’].”\n”;

print ‘<br/>’;

}

The addDocumentBatch.php script is listed.

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$batch=array();

$doc1 = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Engineering as a Service’,”author” => ‘David A. Kelly’)

);

$batch[]=$doc1;

$doc2 = array(

“name” => “MongoDB”,

“type” => “database”,

“count” => 1,

“info” => (object)array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’)

);

$batch[]=$doc2;

$status=$collection->batchInsert($batch);

var_dump($status);

print ‘<br/>’;

foreach ($batch as $doc) {

print ‘Document _id: ‘;

echo $doc[‘_id’].”\n”;

print ‘<br/>’;

}

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Run the PHP script addDocumentBatch.php in the browser with URL

http://localhost:8000/addDocumentBatch.php. As indicated by the output in Figure 3-14, two documents with unique ids get added to MongoDB collection catalog.

  1. Subsequently invoke the find() method for the catalog collection in local database in the Mongo shell to output the documents added.

>use local >db.catalog.find()

The two documents added get listed as shown in Figure 3-15.

Do not delete the catalog collection in the local database as the documents added in a batch shall be used to demonstrate finding a document in the next section.

4. Finding a Single Document

The MongoCollection::findOne() method is used to find a single document from a collection. The findOne() method returns an array consisting of the fields of the document. The method takes as parameters a $query, and the $fields to include in the document returned, and options. The _id field is returned even if not specified in $fields.

MongoCollection::findOne ([ array $query = array() [, array $fields = array()

[, array $options = array() ]]] )

All parameters are optional and if none are specified the first document from the collection is returned. Only one option is supported, maxTimeMS, which is the cumulative time limit in ms for processing the method not including the idle time. If the method does not complete in specified time a MongoExecutionTimeoutException is thrown. The MongoConnectionException is thrown if a connection with the MongoDB server is not established.

  1. Create a PHP script findDocument.php in the C:\php directory. In a try-catch statement, create a MongoClient instance and using the connection create a MongoCollection instance for the catalog collection in the local database.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Invoke the findOne() method on the MongoCollection instance to find a single document. The first document found is returned and could be different for different users.

$document = $collection->findOne();

var_dump($document);

  1. A specific document may be found by specifying the _id field in the array supplied to the findOne() method. The _id field value is constructed using the MongoId class constructor. The _id field value would be different for different users.

$document = $collection->findOne(array(‘_id’ => new MongoId

(“55bcf87a098c6ec80b00002a”)));

var_dump($document);

The PHP script findDocument.php is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$document = $collection->findOne();

var_dump($document);

print ‘<br/>’;

$document = $collection->findOne(array(‘_id’ => new MongoId(“55bcf87a098c6ec80b00002a”)));

var_dump($document);

print ‘<br/>’;

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Run the PHP script in a browser with the URL http://localhost:8000/ findDocument.php. Two documents get displayed in the browser as shown in Figure 3-16.

Again, do not delete the catalog collection in the local database as the documents added in batches shall be used to demonstrate finding documents in the next section.

5. Finding All Documents

The MongoCollection::find() method is used to find all documents that match a specified query. The method syntax takes two parameters, $query and $fields, both of type array and both optional. The _id field is always returned. If a query is not specified all documents are returned. The find() method returns a cursor, represented by a MongoCursor instance, over the result set of the database query.

MongoCursor MongoCollection::find ([ array $query = array() [, array $fields = array() ]] )

  1. Create a PHP script findAllDocuments.php in the C:\php directory. In a try- catch statement create a MongoClient instance, which represents a connection with the MongoDB server. Create a MongoCollection instance for the catalog collection in the local database.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Invoke the find() method on the MongoCollection instance and use the iterator_to_array method to convert the cursor returned to an array.

$cursor = $collection->find();

var_dump(iterator_to_array($cursor));

  1. The foreach loop may also be used to iterate over the result set of the database query. For example the _id and catalogId field values are output as follows.

foreach ($cursor as $doc) {

var_dump($doc[“_id”]);

print ‘<br/>’;

var_dump($doc[“info”][“catalogId”]);

}

The findAllDocuments.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

print ‘Number of Documents: ‘;

var_dump($collection->count());

print ‘<br/>’;

$cursor = $collection->find();

var_dump(iterator_to_array($cursor));

print ‘<br/>’;

foreach ($cursor as $doc) {

var_dump($doc[“_id”]);

print ‘<br/>’;

var_dump($doc[“info”][“catalogId”]);

print ‘<br/>’;

var_dump($doc[“info”][“journal”]);

print ‘<br/>’;

var_dump($doc[“info”][“publisher”]);

print ‘<br/>’;

var_dump($doc[“info”][“edition”]);

print ‘<br/>’;

var_dump($doc[“info”][“title”]);

print ‘<br/>’;

var_dump($doc[“info”][“author”]);

print ‘<br/>’;

}

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Run the PHP script in a browser with the URL http://localhost:8000/php. All the documents in the catalog collection in the local database get displayed. The field values for each of the documents also get displayed as shown in Figure 3-17.

6. Finding a Subset of Fields and Documents

The find() method takes two parameters of type array, $query and $fields, both of which are optional. To select a subset of fields from a subset of documents parameter values for both may be specified.

  1. First, add a document set using the following script, addDocumentSet.php in the C:\php directory.

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$doc = array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Engineering as a Service’,”author” => ‘David A. Kelly’);

$status=$collection->insert($doc);

var_dump($status);

print ‘<br/>’;

$doc = array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,

“title” => ‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’);

$status=$collection->insert($doc); var_dump($status);

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Copy the script to the C:\php directory and run with URL http://localhost:8000/addDocumentSet.php.
  2. Create another PHP script, findDocumentSet.php, in the C:\php directory to find a subset of fields and documents.
  3. Create a MongoCollection instance for catalog collection in the local database as before.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Specify the array of key=>value pairs for which documents are to be found. As an example select all documents with catalogId as catalog1.

$query = array(‘catalogId’=>’catalog1’);

  1. Specify an array of fields to select from the document/s found. As an example select the title and author fields.

$fields = array(‘title’ => true, ‘author’ => true);

  1. Invoke the find() method using the $query and $fields args to get a cursor over the result set.

$cursor = $collection->find($query, $fields);

  1. Using a while loop iterate over the result to output the document fields returned. The hasNext() method in MongoCursor moves the cursor to the next document and the getNext() method gets the next document.

while ($cursor->hasNext())

{

var_dump($cursor->getNext());

}

?>

The findDocumentSet.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$query = array(‘catalogId’=>’catalog1’);

$fields = array(‘title’ => true, ‘author’ => true);

$cursor = $collection->find($query, $fields);

while ($cursor->hasNext())

{

var_dump($cursor->getNext());

}

}catch (MongoConnectionException $e)

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo $e;

exit();

}

?>

9. Run the findDocumentSet.php script in a browser with URL http://localhost:8000/findDocumentSet.php to output the selected fields from the selected documents as shown in Figure 3-18

  1. To select all documents specify the query as follows.

$query = array();

When the findDocumentSet.php script is run in the browser to select all documents, the selected fields from all documents get selected as shown in Figure 3-19.

7. Updating a Document

The MongoCollection::update() method is used to update one or more documents based on a specified criteria. The method returns a status array if w option is set or returns a boolean. The method syntax takes the $criteria, $new_object and $options parameters all of type array.

MongoCollection::update ( array $criteria , array $new_object [, array $options = array() ] )

The method parameters are discussed in Table 3-6.

Next, we shall update some documents.

  1. First, we need to add the documents to update. Run the addDocumentBatch. php script with URL http://localhost:8000/addDocumentBatch.php as shown in Figure 3-20 to add two documents to the catalog collection in the local database. The document _id is output. We shall use these _id values to update the documents. The id values would be different for different users.

  1. Create a PHP script updateDocument.php in the C:\php directory. In a try-catch statement create a connection with MongoDB using a MongoClient instance. Create a MongoCollection instance for the catalog collection in the local database.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Specify the $criteria for the document to update by setting the _id field in the array to a MongoId instance constructed from 53f3d425098c6e2410000065, which is the _id for one of the documents added to the catalog collection with addDocumentBatch.php.The _id value would be different for different users.

$criteria = array(“_id” => new MongoId(“55bba68a098c6e1c19000043 “));

  1. Specify a $new_object using key=>value pairs for the replacement document.

Add a new field “updated” set to “true.”

$new_object = array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′,”title” =>

‘Engineering As a Service’,”author” => ‘Kelly, David A.’, “updated”=>true);

  1. Invoke the update() method using the $criteria and $new_object and using an options array with upsert set to false.

$status=$collection->update($criteria,$new_object, array(“upsert” => false));

var_dump($status);

  1. Similarly, update another document.

$criteria = array(“_id” => new MongoId(“55bba68a098c6e1c19000044”));

$new_object = array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′,”title” =>

‘Quintessential and Collaborative’,”author” => ‘Haunert, Tom’, “updated”=>true);

$status=$collection->update($criteria,$new_object, array(“upsert” => false));

var_dump($status);

We set the upsert option to false in the preceding document updates. Next we shall invoke the update method using upsert option set to true.

To demonstrate that upsert adds new document if a document for the $criteria is not found specify a $criteria using a _id that does not already exist in the database. The same _id value may be used by different users as in the updateDocument.php script listed.

$criteria = array(“_id” => new MongoId(“53f3d425098c6e2410000064”));

  1. Specify a $new_object replacement document and invoke the update() method with upsert set to true.

$new_object = array(“catalogId” => ‘catalog3’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′);

$status=$collection->update($criteria,$new_object, array(“upsert” => true));

The updateDocument.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$criteria = array(“_id” => new MongoId(“55bba68a098c6e1c19000043”));

$new_object = array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′,”title” =>

‘Engineering As a Service’,”author” => ‘Kelly, David A.’, “updated”=>true);

$status=$collection->update($criteria,$new_object, array(“upsert” => false));

var_dump($status);

print ‘<br/>’;

$criteria = array(“_id” => new MongoId(“55bba68a098c6e1c19000044”));

$new_object = array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′,”title” =>

‘Quintessential and Collaborative’,”author” => ‘Haunert, Tom’, “updated”=>true);

$status=$collection->update($criteria,$new_object, array(“upsert” => false));

var_dump($status); print ‘<br/>’;

$criteria = array(“_id” => new MongoId(“53f3d425098c6e2410000064”));

$new_object = array(“catalogId” => ‘catalog3’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ’11-12-2013′);

$status=$collection->update($criteria,$new_object, array(“upsert” => true));

var_dump($status);

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

  1. Run the updateDocument.php script in a browser using URL

http://localhost:8000/updateDocument.php. Two documents get updated and one document gets upserted. The updatedExisting key is true in two of the status arrays and false in one status array as shown in Figure 3-21.

  1. Run the following JavaScript method in Mongo shell

>use local

>db.catalog.find()

The updated/upserted documents get listed as shown in Figure 3-22.

8. Updating Multiple Documents

In the preceding section we mentioned the multiple option in the update() method to update multiple documents. In this section we shall use the multiple option.

  1. Create a PHP script updateMultiDocuments.php in the C:\php directory. In a try-catch statement create a MongoCollection instance as before.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Add two documents using the insert() method. Do not include the journal field in the documents added as we shall be adding the field using the update() method.

$collection->insert(array(“catalogId” => ‘catalog1’, “publisher” => ‘Oracle Publishing’,

“edition” => ‘November December 2013’,”title” => ‘Engineering as a Service’,”author” => ‘David A. Kelly’));

$collection->insert(array(“catalogId” => ‘catalog2’, “publisher” => ‘Oracle Publishing’,

“edition” => ‘November December 2013’,”title” => ‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’));

  1. We shall add the journal field to the documents added using the update operator $set in the update method with the multiple option set to true.

$newdata = array(‘$set’ => array(“journal” => “Oracle Magazine”));

  1. Invoke the update() method using the $criteria as documents with edition field as November December 2013, the $newdata for fields to update, and options array with multiple set to true.

$status=$collection->update(array(“edition” => “November December 2013”), $newdata,array(“multiple” => true));

The updateMultiDocuments.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$collection->insert(array(“catalogId” => ‘catalog1’, “publisher” => ‘Oracle Publishing’,

“edition” => ‘November December 2013’,”title” => ‘Engineering as a Service’,”author” => ‘David A. Kelly’));

$collection->insert(array(“catalogId” => ‘catalog2’, “publisher” => ‘Oracle Publishing’,

“edition” => ‘November December 2013’,”title” => ‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’));

$newdata = array(‘$set’ => array(“journal” => “Oracle Magazine”));

$status=$collection->update(array(“edition” => “November December 2013”),

$newdata,array(“multiple” => true));

var_dump($status);

}

catch (MongoConnectionException $e)

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo $e;

exit();

}

?>

  1. Run the updateMultiDocuments.php script in a browser using the URL http://localhost:8000/updateMultiDocuments.php. In the output updatedExisting key value is true with nModified key value as 2, which indicates that two existing documents got updated as shown in Figure 3-23.

  1. Run the db.catalog.find() method in Mongo shell to list the updated documents. As shown in the output the documents include the journal field as shown in Figure 3-24.

9. Saving a Document

By default the insert() method does not add a modified document if the document already exists in the database. The MongoCollection class provides another method to insert a modified document. The MongoCollection::save() method saves a document to a collection. Save is different from insert in that the document to be saved may already exist in the database. In this section we shall add two documents using the insert() method and subsequently invoke the save() method to save the same documents with modified field values for some of the fields. The syntax of the save method is as follows.

MongoCollection::save ( array|object $document [, array $options = array() ] )

  1. Create a PHP script saveDocument.php in the C:\php directory. In the try-catch statement create a MongoCollection instance.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Add two documents using the insert() method.

$doc1 = array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’, “publisher” =>

‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Engineering as a Service’,”author” => ‘David A. Kelly’);

$status=$collection->insert($doc1);

$doc2 =array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’,

“publisher” => ‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” =>

‘Quintessential and Collaborative’,”author” => ‘Tom Haunert’); $status=$collection->insert($doc2);

  1. Subsequently modify some of the field values in the two documents and invoke the save() method on the modified documents.

$doc1[‘edition’]= ’11-12-2013′;

$dod[‘author’] = ‘Kelly, David A.’;

$doc1[‘updated’]=true;

$status=$collection->save($doc1);

$doc2[‘edition’]=’11-12-2013′;

$doc2[‘author’] = ‘Haunert, Tom’;

$doc2[‘updated’]=true;

$status=$collection->save($doc2);

The save() method saves the documents with the modified field values. If we had used the insert method to save the modified documents we would have received an error. The saveDocument.php script is listed:

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$doc1 = array(“catalogId” => ‘catalog1’, “journal” => ‘Oracle Magazine’, “publisher” => ‘Oracle

Publishing’, “edition” => ‘November December 2013’,”title” => ‘Engineering as a Service’,”author” =>

‘David A. Kelly’);

$status=$collection->insert($doc1);

var_dump($status);

print ‘<br/>’;

$doc2 =array(“catalogId” => ‘catalog2’, “journal” => ‘Oracle Magazine’, “publisher” =>

‘Oracle Publishing’, “edition” => ‘November December 2013’,”title” => ‘Quintessential and

Collaborative’,”author” => ‘Tom Haunert’);

$status=$collection->insert($doc2);

var_dump($status);

print ‘<br/>’;

$doc1[‘edition’]= ’11-12-2013′;

$doc1[‘author’] = ‘Kelly, David A.’;

$doc1[‘updated’]=true;

$status=$collection->save($doc1);

var_dump($status);

print ‘<br/>’;

$doc2[‘edition’]=’11-12-2013′;

$doc2[‘author’] = ‘Haunert, Tom’;

$doc2[‘updated’]=true;

$status=$collection->save($doc2);

var_dump($status);

print ‘<br/>’;

}catch ( MongoConnectionException $e )

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}catch(MongoCursorException $e) {

echo ‘<p>w option is set and the write has failed</p>’;

exit();

}

?>

4. Run the PHP script in the browser with the URL http://localhost:8000/ saveDocument.php. Two documents get added. Subsequently the two documents get updated as indicated by the updatedExisting key value true in Figure 3-25.

 

  1. Run the JavaScript method db.catalog.find() in Mongo shell to list the updated documents as shown in Figure 3-26.

10. Removing a Document

The MongoCollection::remove() method to remove a document has the following syntax.

MongoCollection::remove ([ array $criteria = array() [, array $options = array() ]] )

The method parameter $criteria is the query criteria for the document/s to remove. Most of the options such as w, j, fsync, are the same as the other methods. The remove() method provides the justOne option to remove just one document. In this section we shall remove a document from a collection.

  1. First, add some documents using the addDocumentBatch.php script as shown in Figure 3-27.

The db.catalog.find() method in mongo shell should list the two documents added as shown in Figure 3-28.

  1. Create a PHP script removeDocument.php in the C:\php directory. Create a MongoCollection instance as before.

$connection = new MongoClient();

$collection=$connection->local->catalog;

  1. Invoke the remove method with the _id for the document to remove as method arg. The _id field must be supplied as a MongoId instance and would be different for different users.

$id = ’55bba8d9098c6e1c19000049′;

$status=$collection->remove(array(‘_id’ => new MongoId($id)));

The removeDocument.php script is listed:

<?php

try

{

$id = ’55bba8d9098c6e1c19000049′;

$connection = new MongoClient();

$collection=$connection->local->catalog;

$status=$collection->remove(array(‘_id’ => new MongoId($id))); var_dump($status);

}catch (MongoConnectionException $e)

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}

?>

4. Run the removeDocument.php script in a browser with URL http://localhost:8000/removeDocument.php to remove a document as shown in Figure 3-29

If the db.catalog.find() method is run again only one document is listed as shown in the result for the 2nd run of db.catalog.find() Figure 3-30.

The remove() method may be used to remove all documents. As we removed one of the two documents added by running the addDocumentBatch.php script we need to add some more documents to the catalog collection to demonstrate removing all documents as removing a single document would not demonstrate that all or multiple documents got removed.

  1. Run the addDocumentBatch.php script again to add two more documents, which brings the total documents to three.
  2. Next, create a PHP script removeAllDocuments.php in the C:\php directory.

Invoke the remove() method as for removing a single document but supply an empty array.

$status=$collection->remove(array());

The removeAllDocuments.php script is listed.

<?php

try

{

$connection = new MongoClient();

$collection=$connection->local->catalog;

$status=$collection->remove(array());

var_dump($status);

}catch (MongoConnectionException $e)

{

echo ‘<p>Couldn\’t connect to mongodb</p>’;

exit();

}

?>

  1. Run the PHP script with the URL http://localhost:8000/

removeAllDocuments.php. As indicated by n=>int(3) in Figure 3-31 all of the three documents get removed.

The db.catalog.find() if run subsequently does not list any documents. Do not remove the catalog collection in the local database as we shall be demonstrating dropping a collection in the next section.

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *