Inserting a document into a collection in MongoDB with PHP

Assume that we have a MongoDB server installed as a windows service on the same machine as our web server. The server listens on port 33333.

We met a new friend, and we want to save some details about her. That night, before bidding farewell, she said: "Remember me, I am Mary Jane. You can write to me at mary.jane@gmail.com".

Although that's all we have about her, this is sufficient for us to insert a document about Mary into our MongoDB database.

Inserting documents into collections in MongoDB with PHP consists of the following steps:

  • Derive an instance of the MongoCollection class that represents the MongoDB collection to insert documents.
  • Define the document to insert.
  • Define additional options for the insert.
  • Execute the insert function of the MongoCollection instance.

Derive an instance of the MongoCollection class that represents the MongoDB collection to insert documents

<?php

$connection = new Mongo('mongodb://localhost:33333');
$friendCollection = $connection->selectCollection("contactDb", "friend");

?>

To instruct our MongoDB server to help us remember Mary, we first get an instance of the Mongo class that connects to our server. We then utilize the selectionCollection function of the Mongo instance to get an instance of the MongoCollection class that points to the "friend" collection in the "contactDb" database.

Define the document to insert

In PHP, documents are mapped to associative arrays. With that, we can declare an array which contains the two pieces of data which Mary had provided:

<?php

$mary = array(
    'name'  => 'Mary Jane',
    'email' => 'mary.jane@gmail.com'
);

?>

We associate the string "Mary Jane" with the "name" key and the string "mary.jane@gmail.com" with the "email" key.

Define additional options for the insert

We can specify a set of additional options to control how the PHP driver will perform the insertion of Mary's details into the "friend" collection. Such options are specified in an associate array with certain key/value pairs.

<?php

$insertOptions = array(
	'safe'    => true,
	'fsync'   => true,
	'timeout' => 10000
);

?>

To ensure that details provided by Mary are correctly saved into the "friend" collection, we specify a true as the value for the "safe" and "fsync" keys.

With "safe" having a value of true, our PHP program will wait for the database response and throw a MongoCursorException if the insert is unsuccessful. This overrides the default behavior of the insert operation in which the PHP driver is ignorant to whether Mary's details are successfully remembered in the "friend" collection.

With "fsync" having a value of true, our PHP program will force the driver to synchronize the insert to disk before indicating the insert to be successful.

With "timeout" having a value of 10000, our PHP driver will wait for at most 10 seconds for the insert operation to complete. If not, a MongoCursorTimeoutException will be thrown.

Execute the insert function of the MongoCollection instance

Once we have gathered the data to insert and the options to apply in the form of arrays, we are ready to perform the insertion of the document.

<?php

try {
	
	$results = $friendCollection->insert($mary, $insertOptions);
	
	print '<h2>Result from saving Mary\'s details</h2>';
	print '<pre>';
	print_r($results);
	print '</pre>';
	
	print '<h2>Mary\'s details in database</h2>';
	print '<pre>';
	print_r($mary);
	print '</pre>';	
}
catch (MongoCursorException $mce) {
	// Triggered when the insert fails
}
catch (MongoCursorTimeoutException $mcte) {
	// Triggered when insert does not complete within value given by timeout
} // end try -catch 

?>

We insert the document that describes Mary into our "friend" collection via the insert function of the MongoCollection class.

We place the $friendCollection->insert function call in a try clause because of the options that we have specified for the insert operation.

In the event when the document cannot be inserted successfully, a MongoCursorException will be thrown. One such case would be to execute the $friendCollection->insert a second time:


// ...
$results = $friendCollection->insert($mary, $insertOptions);
$results = $friendCollection->insert($mary, $insertOptions);
// ...

If the PHP driver waited more than 10 seconds for a response from the database, a MongoCursorTimeoutException will be thrown.

The results from the document insertion

If we are able to execute $friendCollection->insert without encountering any exceptions, an array containing details of the document insertion will be available via the $results variable. On my machine, I was able to get the following output by executing print_r on the $results array:

Array
(
    [n] => 0
    [connectionId] => 1
    [waited] => 11
    [err] => 
    [ok] => 1
)
  • n points to the number of objects that are affected by the insertion. Since insertion of documents does not affect any objects in the database, n points to a 0.
  • connectionId points to the identification number of the MongoDB connection that was used to perform the document insertion.
  • waited points to the time in milliseconds that the PHP driver had waited for the document insertion to be successful.
  • err points to an error message that describe an error that had occurred during document insertion. Since it had pointed to a null value, we can determine that the document insertion was successful.
  • ok points to a value that indicates whether the document insertion was successful. A value of 1 means that Mary's details were being inserted to the "friend" collection successfully.

Getting the unique id of the document that was just inserted into the MongoDB collection

A MongoDB server will help to generate a unique id for every document that it manages when possible. If the _id key is absent from the document array, our MongoDB server will help us create one during document insertion. Indeed, passing the $mary variable into the print_r function after we call $friendCollection->insert reveals the value of the "_id" key that our MongoDB server had created for us:

Array
(
    [name] => Mary Jane
    [email] => mary.jane@gmail.com
    [_id] => MongoId Object
        (
            [$id] => 502770ad5d79f9800b000009
        )
)

Related posts

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.