MongoDB PHP 7 CRUD Example

We know MongoDB is very popular open source, document based NoSQL database. In this tutorial I am going to create MongoDB PHP CRUD Example.  CRUD means Create, Read, Update and Delete operations. So basically you will add new data (create), fetch data (read), edit existing data (update) and remove existing data (delete) from database.

Prerequisites

Apache HTTP Server 2.4, PHP 7.4.3, MongoDB 4.4.0

How to configure MongoDB with PHP 7

Setup Project Directory

It’s assumed that you have setup Apache and PHP in Windows system.

Now we will create a project root directory called php-7-mongodb-crud under the Apache server’s htdocs folder.

I may not mention the project root directory in subsequent sections and we will assume that we are talking with respect to the project root directory.

PHP MongoDB Connection

Create a file called mongodb_config.php with the following source code.

<?php

class DbManager {

	//Database configuration
	private $dbhost = 'localhost';
	private $dbport = '27017';
	private $conn;
	
	function __construct(){
        //Connecting to MongoDB
        try {
			//Establish database connection
            $this->conn = new MongoDB\Driver\Manager('mongodb://'.$this->dbhost.':'.$this->dbport);
        }catch (MongoDBDriverExceptionException $e) {
            echo $e->getMessage();
			echo nl2br("n");
        }
    }

	function getConnection() {
		return $this->conn;
	}

}

?>

Create Collection

Either you can create the collection in the database or if you do not create collection then while you will insert the record MongoDB will automatically create the collection on the fly.

You can use command db.createCollection(<collection name>, <options>); from the MongoDB command line tool. For our case, I am going to create users collection using the command db.createCollection('users');.

First I switch to my database called roytuts then I try to create the collection but it already exists.

mongodb php 7 crud

CRUD Operations

Single Record Insertion

Insert means new record creation in database. I am going to define the following user which we will inset into users collection in roytuts database.

$user1 = array(
    'first_name' => 'Soumitra',
    'last_name' => 'Roy',
    'tags' => array('developer','admin')
);

Now prepare the SQL statements using BulkWrite() method of MongoDB Driver Manager to insert above user.

$single_insert = new MongoDB\Driver\BulkWrite();
$single_insert->insert($user1);

Now execute the query to make insertion happen using the following statement:

$conn->executeBulkWrite("$dbname.$collection", $single_insert);

Once the above statement gets executed, check the users collection in roytuts database using the command db.users.find(). You should see the following output in the users collection.

mongodb php7 crud

So here I have defined single user object and inserted into the users collection of roytuts database. Notice I have not defined any fields for users collection but still I was able to insert the data into users collection because of its NoSQL(Not only Structured Query Language) nature.

Now you may wonder you have not inserted _id field into the user1 object then from where this _id came along with user1 object? The _id field is primary key for every document. It’s called _id and is also accessible via id and an _id field is mandatory for an object or document in collection. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The _id field is the default field for Bson ObjectId’s and it is, by default, indexed. _id and id are not the same. You may also choose to add a field called id if you want, but it will not be index unless you add an index.

The ObjectId class is the default primary key for a MongoDB document and is usually found in the _id field in an inserted document. It looks like, for an example,

{
    "_id" : ObjectId("5f2a9717a82c0000d00002e2")
}

An ObjectId is a 12 byte binary BSON type that contain any 12 bytes you want. To be helpful in generating ObjectIds, MongoDB drivers and the server will generate them using a default Algorithm.

Available Records Read

Read all available users from users collection in roytuts database using the following piece of code:

$filter = [];
$option = [];

$read = new MongoDB\Driver\Query($filter, $option);

$all_users = $conn->executeQuery("$dbname.$collection", $read);

echo nl2br("List of users:\n");

foreach ($all_users as $user) {
	echo nl2br($user->first_name.' '.$user->last_name.' has following roles:' . "\n");
	foreach ($user->tags as $tag) {
		echo nl2br($tag . "\n");
	}
}

Notice how nl2br() method is used to convert "\n" or "\r\n" into new line break.

At present we have only one user so you will get only one user in the output.

Executing the above code will give you the following output:

mongodb php 7 crud

Multiple Records Insertion

Here is the following code snippets that will insert multiple records into MongoDB:

$user1 = array(
    'first_name' => 'Soumitra',
    'last_name' => 'Roy',
    'tags' => array('developer','admin')
);

$user2 = array(
    'first_name' => 'Arup',
    'last_name' => 'Chatterjee',
    'tags' => array('developer')
);

$inserts = new MongoDB\Driver\BulkWrite();
$inserts->insert($user1);
$inserts->insert($user2);

$conn->executeBulkWrite("$dbname.$collection", $inserts);

If you check database then you will find three records exist in the collection:

mongodb php 7 crud

If you run the available record read code example then you will see the following output:

mongodb php 7 crud

Read Single Record

Read single record from the users collection in roytuts database.

$filter = ['first_name' => 'Arup'];
$option = [];
$read = new MongoDB\Driver\Query($filter, $option);
$single_user = $conn->executeQuery("$dbname.$collection", $read);

echo nl2br("\nSingle user:\n");

foreach ($single_user as $user) {
	echo nl2br($user->first_name.' '.$user->last_name.' has following roles:' . "\n");
	foreach ($user->tags as $tag) {
		echo nl2br($tag . "\n");
	}
}

You will get below output when you run the above code snippets:

mongodb php 7 crud

$filter: Selects a subset of an array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.

$filter has the following syntax:

{ $filter: { input: <array>, as: <string>, cond: <expression> } }

So we are filtering the record on first_name of the user. Therefore we have got single record. If you have multiple users with same name then you have to choose unique field or projection for selecting single record.

Update Single Record

Update user where last_name is Roy.

$single_update = new MongoDB\Driver\BulkWrite();
$single_update->update(
    ['last_name' => 'Roy'],
    ['$set' => ['first_name' => 'Liton', 'last_name' => 'Sarkar']],
    ['multi' => false, 'upsert' => false]
);
$result = $conn->executeBulkWrite("$dbname.$collection", $single_update);

if($result) {
	echo nl2br("Record updated successfully \n");
}

multi (boolean): Update only the first matching document (multi=false), or all matching documents (multi=true).
upsert (boolean): If filter does not match an existing document, insert a single document. The document will be created from newObj if it is a replacement document (i.e. no update operators); otherwise, the operators in newObj will be applied to filter to create the new document.

Output:

Record updated successfully

So here we are first find the record which is having last_name as ‘Roy’ and updating with first_name as ‘Liton’ and last_name as ‘Sarkar’.

Now check the users collection in roytuts database. Notice though we had two users with last name Roy but only one record got updated because I have updated only one record using 'multi' => false.

mongodb php 7 crud

Multiple Update

Update multiple rows using single query.

$updates = new MongoDB\Driver\BulkWrite();
$updates->update(
    ['last_name' => 'Roy'],
    ['$set' => ['first_name' => 'Liton', 'last_name' => 'Sarkar']],
    ['multi' => true, 'upsert' => true]
);
$result = $conn->executeBulkWrite("$dbname.$collection", $updates);

Now you can verify the records in database:

mongodb php 7 crud

Update multiple rows using multiple queries.

$updates = new MongoDB\Driver\BulkWrite();
$updates->update(
    ['last_name' => 'Roy'],
    ['$set' => ['first_name' => 'Liton', 'last_name' => 'Sarkar']],
    ['multi' => false, 'upsert' => false]
);
$updates->update(
    ['last_name' => 'Chatterjee'],
    ['$set' => ['first_name' => 'Soumitra', 'last_name' => 'Roy']],
    ['multi' => false, 'upsert' => false]
);
$result = $conn->executeBulkWrite("$dbname.$collection", $updates);

Delete Single/Multiple Record(s)

Delete user where first_name is Liton.

$delete = new MongoDB\Driver\BulkWrite();
$delete->delete(
    ['first_name' => 'Liton'],
    ['limit' => 1]
);

$result = $conn->executeBulkWrite("$dbname.$collection", $delete);

if($result) {
	echo nl2br("Record deleted successfully \n");
}

limit (boolean): Delete all matching documents (limit=0), or only the first matching document (limit=1).

You can check the users collection under roytuts database.

Deletion using multiple queries.

$deletes = new MongoDB\Driver\BulkWrite();
$deletes->delete(
    ['first_name' => 'Liton'],
    ['limit' => 1]
);

$deletes->delete(
    ['first_name' => 'Arup'],
    ['limit' => 1]
);

$result = $conn->executeBulkWrite("$dbname.$collection", $deletes);

if($result) {
	echo nl2br("Record deleted successfully \n");
}

Source Code

Download

Thanks for reading.

3 thoughts on “MongoDB PHP 7 CRUD Example

  1. Thank you very much!! You help me a lot with that CRUD, I was not able to unite php with mongodb!! Thanks

Leave a Reply

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