MongoDB PHP 7 CRUD Example

We know MongoDB is very popular open source, document based NoSQL database. In this tutorial we will create MongoDB PHP 7 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.

Please make sure you have read how to configure MongoDB with PHP 7 for XAMPP before reading MongoDB PHP 7 CRUD Example.

Prerequisites

Knowledge of PHP and Database

Please go through following steps in order to create MongoDB PHP 7 CRUD Example

Step 1. Create a php file called php-mongo.php under <xampp installation directory>/xampp/htdocs/php directory.

Step 2. Define the connection object as shown in my tutorial how to configure MongoDB with PHP 7 for XAMPP.

Step 3. Create first roytuts database and users collection in the MongoDB for performing MongoDB PHP 7 CRUD Example using MongoDB Compass from the option: CREATE DATABASE

mongodb php 7 crud

Once created you will find similar to below image

mongodb php 7 crud

Step 4. Now we will do CRUD operations

Record insert example

Insert means new record creation in database.

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.$c_users", $single_insert);

Once the above statement gets executed, check the users collection in roytuts database. You should see the following output in the users collection.

mongodb php7 crud

So here we have defined single user object and inserted into the users collection of roytuts database. Notice we have not defined any fields for users collection but still we are 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 insert _id field into the user1 object then 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("54759eb3c090d83494e2d804")
}

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. For more information you may read http://mongodb.github.io/node-mongodb-native/2.0/tutorials/objectid/.

Multiple users insert example

$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.$c_users", $inserts);

Record read example

Read all available users from users collection in roytuts database

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

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

echo nl2br("All 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");
	}
}

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

All users => 
Soumitra Roy has following roles
developer
admin

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 have got only one user in the output.

Read single record from the users collection in roytuts database.

$filter = ['first_name' => 'Soumitra'];
$option = [];
$read = new MongoD\BDriver\Query($filter, $option);
$single_user = $conn->executeQuery("$dbname.$c_users", $read);

echo nl2br("nSingle user => rn");

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

All users => 
Soumitra Roy has following roles
developer
admin

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 record example

Update user where last_name if 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.$c_users", $single_update);

if($result) {
	echo nl2br("Record updated successfullyn");
}

multi (boolean): Update only the first matching document (multi=false), or all matching documents (multi=true). FALSE
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.

mongodb php 7 crud

Multiple users update example

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.$c_users", $updates);

Also check below to update multiple rows using different 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.$c_users", $updates);

Delete record example

Delete user where first_name is Liton.

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

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

if($result) {
	echo nl2br("Record deleted successfullyn");
}

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

Output:

Record deleted successfully

Now check the users collection in roytuts database.

mongodb php 7 crud

So now users collection is again got empty after deleting the record.

Multiple users 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.$c_users", $deletes);

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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