How to Perform CRUD in MongoDB Document using PHP Part4

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In this tutorial which is part 4 of “How to Perform CRUD in MongoDB Document using PHP,” we’ll explain how to delete a MongoDB document using PHP MongoDBDriverBulkWrite. It’s a fact that the basics of application development include the ability to achieve CRUD (Create, Read, Update, Delete). The “D” is the practice of deleting documents and it’s an important part of healthy database management. That’s because outdated documents take up space and slow down the server. Today you’ll learn how to delete a MongoDB document using both MongoDBDriverManager and PHP Library. This tutorial is designed to benefit users who want to try MongoDB on their PHP projects, so let’s begin.

How to Delete MongoDB Document using PHP

Prerequisites:

  • MongoDB – Install the latest version that is compatible with your OS.

  • MongoDB PHP Driver – Install the correct PHP driver that is recommended for your version of MongoDB.

  • Verify that you have the MongoDB driver installed. Use the command pecl search:

1
pecl search mongo
  • A successful result is shown below:
1
2
3
4
5
.Matched packages, channel pecl.php.net:
=======================================
Package Stable/(Latest) Local
mongo 1.6.16 (stable) MongoDB database driver
mongodb 1.6.0alpha1 (alpha) 1.5.3 MongoDB driver for PHP
  • Verify the PHP version you installed with this command:
1
php --version
  • You should see a similar result to this one:
1
2
3
4
PHP 7.2.15-0ubuntu0.18.04.2 (cli) (built: Mar 22 2019 17:05:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.15-0ubuntu0.18.04.2, Copyright (c) 1999-2018, by Zend Technologies

Start MongoDB using the sudo command

  • Press Ctrl+Alt+T because it opens your terminal.

  • Start MongoDB. Use sudo at the command line to give permissions.

1
2
sudo systemctl start mongod
sudo systemctl status mongod
  • It should look closely to this:
1
2
3
4
5
6
7
8
9
10
â— mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
Active: active (running) since Mon 2019-04-22 19:27:02 PST; 8min ago
Docs: https://docs.mongodb.org/manual
Main PID: 6598 (mongod)
CGroup: /system.slice/mongod.service
└─6598 /usr/bin/mongod --config /etc/mongod.conf

Apr 22 19:27:02 teamsolo systemd[1]: Started MongoDB Database Server.
lines 1-9/9 (END)

>NOTE: This is the 4th part of a series. Before you proceed, review parts 1 through 3 in the series to confirm that you have installed MongoDB and the required driver properly.

About the delete.php Page

  • You will use delete.php page to delete a MongoDB document you select for removal.

Check the id in the script

  • The id setting must be right in order to everything to work seamlessly. If it’s incorrect, it will redirect to the index.php page.
1
2
3
4
5
6
7
<?php

require_once('../../../private/initialize.php'); // (1)
if(!isset($_GET['id'])) { // (2)
redirect_to(url_for('/staff/subjects/index.php'));
}
$id = $_GET['id']; // (3)

(1) Add initialize.php a single time.

(2) Find the id and check the setting. (Use superglobals $_GET to obtain the ‘id). Here is where the setting will redirect the id to index.php if it is incorrect.

(3) Set the superglobals $_GET ['id'] value to the variable $id setting. *** `php $subject = find_subject_by_id($id); // (4)

if(is_post_request()) { // (5) delete_subject_by_id($id); }

?> `

(4) Matches the id field with the variable $id to find the document to delete.

(5) The delete_subject_by_id($id); function occurs when a POST request tells the script to delete the document that has an id that is the same as the id field criteria. ***

About the delete_subject_by_id($id) function and MongoDBDriverBulkWrite

1
2
3
4
5
6
7
8
// Using the MongoDBDriverManager
global $db; // (1)
$delRec = new MongoDBDriverBulkWrite;
$delRec->delete([ // (2)
'_id' =>new MongoDBBSONObjectID($id)], ['limit' => 1]);
$writeConcern = new MongoDBDriverWriteConcern(
MongoDBDriverWriteConcern::MAJORITY, 1000);
$result = $db->executeBulkWrite('abi_db.subjects', $delRec, $writeConcern);

(1) Connect MongoDB by using initialize.php which includes the $db call variable. The MongoDBDriverBulkWrite gathers the information that will be sent to the server.

(2) The chosen document is the only one that gets deleted because the $id value is the same as the document’s id. To make sure, check that the parameter limit is set. The executeBulkWrite sends the request to the server.


1
2
3
4
5
6
7
// Using the PHP Library
global $con; // (1)
$db = $con->abi_db; // (2)
$collection = $db->subjects; // (3)
$delRec = $collection->deleteOne( // (4)
['_id' =>new MongoDBBSONObjectID($id)], ['limit' => 1]
);

(1) Connect to MongoDB. Here, the initialize.php has the $con variable to call.

(2) The abi_db is connected.

(3) The $subjects collection is connected.

(4) The deleteOne query selector deletes a limit of “1” document with the specified value indicated by the $id.

  • Store in the PHP file query_functions.php the function delete_subject_by_id($id) so you can use it again whenever you need to.
1
2
3
if($delRec){
redirect_to(the_url('/staff/subjects/index.php'));
}
  • Now, a successful deletion is finished, it will redirect to the index.php page. This is what you want to happen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php $page_title = 'Delete Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>




["">« Back to List](https://intern.textbroker.com/a/teamorder-write-submit.php)
<?php
foreach($subject as $row){ ?>



# Delete Subject



Are you sure you want to delete this subject?



<?php echo html_special(""$row->topic_name""); ?>


<form action="" <?php="<?php" echo="echo" the_url('/staff/subjects/delete.php?id=" . html_special(uEncode(""$row-">_id""))); ?>"" method=""post"">





</form>


<?php }?>



<?php include(SHARED_PATH . '/staff_footer.php'); ?>
  • Go ahead and save the delete.php script above.

  • You can view this PHP page too. Go to the index.php page, click the link for “Delete” in that page. It should appear similar to this:

delete.php page

Conclusion:

This tutorial, part 4 in the series of “How to Perform CRUD in MongoDB Document using PHP,” focused on deleting MongoDB Documents using PHP MongoDBDriverBulkWrite. The process also involves MongoDBDriverManager and the PHP Library. Refer to these steps on any PHP project. Just in case you would like to see the whole script all laid out without breaks in the code, it is shown below.

The whole script showing how to delete a MongoDB document in PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php

require_once('../../../private/initialize.php');

if(!isset($_GET['id'])) {
redirect_to(url_for('/staff/subjects/index.php'));
}
$id = $_GET['id'];

$subject = find_subject_by_id($id);

if(is_post_request()) {
delete_subject_by_id($id);
}

?>

<?php $page_title = 'Delete Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>




["">« Back to List](https://intern.textbroker.com/a/teamorder-write-submit.php)
<?php
foreach($subject as $row){ ?>



# Delete Subject



Are you sure you want to delete this subject?



<?php echo h(""$row->topic_name""); ?>


<form action="" <?php="<?php" echo="echo" the_url('/staff/subjects/delete.php?id=" . html_special(u(""$row-">_id""))); ?>"" method=""post"">





</form>


<?php }?>



<?php include(SHARED_PATH . '/staff_footer.php'); ?>

Check out Part 1

Check out Part 2

Check out Part 3

Check out Part 4

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.