Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Perform CRUD operations on MongoDB with PHP

Save for later
  • 6 min read
  • 17 Mar 2018

article-image

[box type="note" align="" class="" width=""]This article is an excerpt from the book Mastering MongoDB 3.x authored by Alex Giamas. This book covers the key concepts, and tips & tricks needed to build fault-tolerant applications in MongoDB. It gives you the power to become a true expert when it comes to the world’s most popular NoSQL database.[/box]

In today’s tutorial, we will cover the CRUD (Create, Read, Update and Delete) operations using the popular PHP language with the official MongoDB driver.

Create and delete operations

To perform the create and delete operations, run the following code:

$document = array( "isbn" => "401", "name" => "MongoDB and PHP" );

$result = $collection->insertOne($document);

var_dump($result);

This is the output:

MongoDBInsertOneResult Object

(

[writeResult:MongoDBInsertOneResult:private] =>

MongoDBDriverWriteResult Object

(

[nInserted] => 1

[nMatched] => 0

[nModified] => 0

[nRemoved] => 0

[nUpserted] => 0

[upsertedIds] => Array

(

)

[writeErrors] => Array

(

)

[writeConcernError] =>

[writeConcern] => MongoDBDriverWriteConcern Object

(

)

)

[insertedId:MongoDBInsertOneResult:private] => MongoDBBSONObjectID Object

(

[oid] => 5941ac50aabac9d16f6da142

)

[isAcknowledged:MongoDBInsertOneResult:private] => 1

)

The rather lengthy output contains all the information that we may need. We can get the ObjectId of the document inserted; the number of inserted, matched, modified, removed, and upserted documents by fields prefixed with n; and information about writeError or writeConcernError.

There are also convenience methods in the $result object if we want to get the Information:

  • $result->getInsertedCount(): To get the number of inserted objects
  • $result->getInsertedId(): To get the ObjectId of the inserted document

We can also use the ->insertMany() method to insert many documents at once, like this:

$documentAlpha = array( "isbn" => "402", "name" => "MongoDB and PHP, 2nd Edition" );

$documentBeta = array( "isbn" => "403", "name" => "MongoDB and PHP, revisited" );

$result = $collection->insertMany([$documentAlpha, $documentBeta]);

print_r($result);

The result is:

(

[writeResult:MongoDBInsertManyResult:private] =>

MongoDBDriverWriteResult Object

(

[nInserted] => 2

[nMatched] => 0

[nModified] => 0

[nRemoved] => 0

[nUpserted] => 0

[upsertedIds] => Array

(

)

[writeErrors] => Array

(

)

[writeConcernError] =>

[writeConcern] => MongoDBDriverWriteConcern Object

(

)

)

[insertedIds:MongoDBInsertManyResult:private] => Array

(

[0] => MongoDBBSONObjectID Object

(

[oid] => 5941ae85aabac9d1d16c63a2

)

[1] => MongoDBBSONObjectID Object

(

[oid] => 5941ae85aabac9d1d16c63a3

)

)

[isAcknowledged:MongoDBInsertManyResult:private] => 1

)

Again, $result->getInsertedCount() will return 2, whereas $result->getInsertedIds() will return an array with the two newly created

ObjectIds:

array(2) {

[0]=>

object(MongoDBBSONObjectID)#13 (1) {

["oid"]=>

string(24) "5941ae85aabac9d1d16c63a2"

}

[1]=>

object(MongoDBBSONObjectID)#14 (1) {

["oid"]=>

string(24) "5941ae85aabac9d1d16c63a3"

}

}

Deleting documents is similar to inserting but with the deleteOne() and deleteMany() methods; an example of deleteMany() is shown here:

$deleteQuery = array( "isbn" => "401");

$deleteResult = $collection->deleteMany($deleteQuery);

print_r($result);

print($deleteResult->getDeletedCount());

Here is the output:

MongoDBDeleteResult Object

(

[writeResult:MongoDBDeleteResult:private] => MongoDBDriverWriteResult Object

(

[nInserted] => 0

[nMatched] => 0

[nModified] => 0

[nRemoved] => 2

[nUpserted] => 0

[upsertedIds] => Array

(

)

[writeErrors] => Array

(

)

[writeConcernError] =>

[writeConcern] => MongoDBDriverWriteConcern Object

(

)

)

[isAcknowledged:MongoDBDeleteResult:private] => 1

)

2

In this example, we used ->getDeletedCount() to get the number of affected documents, which is printed out in the last line of the output.

Bulk write

The new PHP driver supports the bulk write interface to minimize network calls to MongoDB:

$manager = new MongoDBDriverManager('mongodb://localhost:27017');

$bulk = new MongoDBDriverBulkWrite(array("ordered" => true));

$bulk->insert(array( "isbn" => "401", "name" => "MongoDB and PHP" ));

$bulk->insert(array( "isbn" => "402", "name" => "MongoDB and PHP, 2nd Edition" ));

$bulk->update(array("isbn" => "402"), array('$set' => array("price" => 15)));

$bulk->insert(array( "isbn" => "403", "name" => "MongoDB and PHP,

revisited" ));

$result = $manager->executeBulkWrite('mongo_book.books', $bulk);

print_r($result);



The result is:



MongoDBDriverWriteResult Object

(

[nInserted] => 3



[nMatched] => 1

[nModified] => 1

[nRemoved] => 0

[nUpserted] => 0

[upsertedIds] => Array

(

)

[writeErrors] => Array

(

)

[writeConcernError] =>

[writeConcern] => MongoDBDriverWriteConcern Object

(

)

)

In the preceding example, we executed two inserts, one update, and a third insert in an ordered fashion. The WriteResult object contains a total of three inserted documents and one modified document.

The main difference compared to simple create/delete queries is that executeBulkWrite() is a method of the MongoDBDriverManager class, which we instantiate on the first line.

Read operation

Querying an interface is similar to inserting and deleting, with the findOne() and find() methods used to retrieve the first result or all results of a query:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
$document = $collection->findOne( array("isbn" => "101") );

$cursor = $collection->find( array( "name" => new

MongoDBBSONRegex("mongo", "i") ) );

In the second example, we are using a regular expression to search for a key name with the value mongo (case-insensitive).

Embedded documents can be queried using the . notation, as with the other languages that we examined earlier in this chapter:

$cursor = $collection->find( array('meta.price' => 50) );

We do this to query for an embedded document price inside the meta key field.

Similarly to Ruby and Python, in PHP we can query using comparison operators, like this:

$cursor = $collection->find( array( 'price' => array('$gte'=> 60) ) );

Querying with multiple key-value pairs is an implicit AND, whereas queries using $or, $in, $nin, or AND ($and) combined with $or can be achieved with nested queries:

$cursor = $collection->find( array( '$or' => array(

array("price" => array( '$gte'

=> 60)),

array("price" => array( '$lte'

=> 20))

)));

This finds documents that have price>=60 OR price<=20.

Update operation

Updating documents has a similar interface with the ->updateOne() OR ->updateMany() method.

The first parameter is the query used to find documents and the second one will update our documents.

We can use any of the update operators explained at the end of this chapter to update in place or specify a new document to completely replace the document in the query:

$result = $collection->updateOne(

array( "isbn" => "401"),

array( '$set' => array( "price" => 39 ) )

);

We can use single quotes or double quotes for key names, but if we have special operators starting with $, we need to use single quotes. We can use array( "key" => "value" ) or ["key" => "value"]. We prefer the more explicit array() notation in this book.

The ->getMatchedCount() and ->getModifiedCount() methods will return the number of documents matched in the query part or the ones modified from the query. If the new value is the same as the existing value of a document, it will not be counted as modified.

We saw, it is fairly easy and advantageous to use PHP as a language and tool for performing efficient CRUD operations in MongoDB to handle data efficiently.

If you are interested to get more information on how to effectively handle data using MongoDB, you may check out this book Mastering MongoDB 3.x.

perform-crud-operations-on-mongodb-with-php-img-0