How to Delete MongoDB Document using PHP
Introduction
Managing your MongoDB documents includes deleting the ones you don’t need. That’s because excess data tends to bog down operations and slows the process of finding the right documents that you want to analyze. If you’re new to MongoDB, it’s fun to learn about deleting documents using PHP MongoDBDriverBulkWrite. You can accomplish the task in a variety of ways. Discover them in this step-by-step tutorial that explains how to delete MongoDB documents using PHP.
Prerequisites:
MongoDB – Install the community MongoDB version, then start it.
MongoDB PHP Driver – Install a compatible driver. Verify everything matches up with this Match the driver with your stable MongoDB version.
Check your driver. In a terminal window, use the command
pecl search mongo
.
1 | pecl search mongo |
- When the packages match, you’ll see a result like the one 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 |
- It’s a good idea to check your installed PHP version with this command:
1 | php --version |
- Everything looks good when you see a result like this:
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 |
- Here’s a table that shows the different PHP driver versions and the corresponding MongoDB versions. Use it as a guide.
PHP Driver | PHP 5.4 | PHP 5.5 | PHP 5.6 | PHP 7.0 | PHP 7.1 | PHP 7.2 | PHP 7.3 |
---|---|---|---|---|---|---|---|
mongoDB1.5 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | |
mongoDB1.4 | ✓ | ✓ | ✓ | ✓ | ✓ | ||
mongoDB1.3 | ✓ | ✓ | ✓ | ✓ | ✓ | ||
mongoDB1.2 | ✓ | ✓ | ✓ | ✓ | ✓ | ||
mongoDB1.1 | ✓ | ✓ | ✓ | ✓ | ✓ | ||
mongoDB1.0 | ✓ | ✓ | ✓ |
Use Mongo Shell to Start the MongoDB Database
In a terminal window, press Ctrl+Alt+T.
Use two
sudo
commands to:
(1) Allow yourself permission to access MongoDB (2) Start it up (3) Verify the status of the server
1 2 | sudo systemctl start mongod sudo systemctl status mongod |
- A successful result resembles 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) |
Use PHP to Delete a Document with the limit
parameter option
- This simple script deletes a single document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Using MongoDB\Driver\Manager $bulk = new MongoDB\Driver\BulkWrite; $bulk->delete(['topic_name' => ""Delete MongoDB Document""], ['limit' => 1]); $manager = new MongoDB\Driver\Manager('mongodb://localhost:27017'); $result = $manager->executeBulkWrite('database.myCollection', $bulk); // Using PHP Library $con = new MongoDB\Client(""mongodb://localhost:27017""); $db = $con->databaseabi_db; $collection = $db->myCollectiontopic; $delRec = $collection->deleteOne( ['topic_name' => ""Delete MongoDB Document""], ['limit' => 1] ); |
""Delete MongoDB Document""
is the value of thetopic_name
field.There’s a limit to finding the number of documents to delete. This is specified by the
limit
parameter.
>NOTE: If you don’t know the document id
and want to delete a document, try using the limit
parameter in that case as well.
Use Document id
to Delete a MongoDB Document
- If you know the document
id
, you can use that information to delete a document in MongoDB.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Using MongoDB\Driver\Manager $delRec = new MongoDB\Driver\BulkWrite; $delRec->delete(['_id' =>new MongoDB\BSON\ObjectID($id)], ['limit' => 1]); $result = $db->executeBulkWrite('database.myCollection', $delRec); // Using PHP Library $con = new MongoDB\Client(""mongodb://localhost:27017""); $db = $con->database; $collection = $db->myCollection; $delRec = $collection->deleteOne( [['_id' =>new MongoDB\BSON\ObjectID($id)], ['limit' => 1]] ); |
- According to the script above, when the
$_id
variable’s value is the same as a document’sid
, that document will be deleted.
>NOTE : The MongoDB\BSON\ObjectID
function is always used with the id
parameter when you want to delete a document. This is necessary when you both the value of an ObjectID
and a document’s id
match.
>
> By the way, the id
method of deletion is a great way to delete one particular document.
Use PHP to Delete Multiple Documents
- The
position
field a value plays a key role in this PHP deletion method.
1 2 3 4 5 6 7 8 9 10 | // Using MongoDB\Driver\Manager $delRec = new MongoDB\Driver\BulkWrite; $delRec->delete(['position' => 2]); $result = $db->executeBulkWrite('database.myCollection', $delRec); // Using PHP Library $con = new MongoDB\Client(""mongodb://localhost:27017""); $db = $con->databaseabi_db; $collection = $db->myCollectiontopic; $deleteResult = $collection->deleteMany(['position' => 2]); |
- See the last line in the script. Note the
position
field value which is “2.” MongoDB documents with that field value will be deleted.
>NOTE: The script comes in handy when you need to delete duplicates or many documents with equal values.
Use PHP to Delete One MongoDB Document
1 2 3 4 5 | // Using PHP Library $con = new MongoDB\Client(""mongodb://localhost:27017""); $db = $con->; $collection = $db->; $collection->deleteOne(['topic_name' => 'AbiInc']); |
- To delete one document use the
MongoDB\Collection::deleteOne()
method. It’s a fast way to delete just one document based on a filter. TheMongoDB\DeleteResult
is returned in the search results.
>NOTE : With the PHP method above, only the first document that matches the deletion criteria when there are multiples.
Conclusion
In this tutorial, we discussed how to delete documents using PHP, specifically, deleting documents using PHP MongoDB Driver Bulk Write. We went over removing single and multiple documents. In addition, we showed how to discard a document by its document id
. Using the limit
parameter or position
field are other methods that we touched on. Whether you are a new user or an experienced one, you can refer back to this tutorial. Use it anytime to determine which MongoDB document deletion method best suits your specific project needs.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started