Table of Content
Deleting records in MongoDB is a common task. You might need to clear old data, remove outdated entries, or handle sensitive information for compliance. Let’s go step by step to see how you can delete documents from MongoDB using PHP.
Deleting a Single Document
Sometimes, you only need to delete a specific document. For instance, let’s say you want to delete a user with a specific email address. Here is how you can do it:
$deleteResult = $collection->deleteOne([
'email' => 'user@example.com'
]);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
In this example:
- The
deleteOnemethod is used to delete the first document matching the query. - The query specifies the criteria for deletion (
email => 'user@example.com'). - The
getDeletedCountmethod returns the number of documents deleted.
Anyway, in the following section, you will learn how to delete multiple documents in MongoDB in PHP.
Deleting Multiple Documents
If you need to delete more than one document, such as all users who have been inactive for over a year, you can use the deleteMany method. Here is an example:
$deleteResult = $collection->deleteMany([
'last_active' => [
'$lt' => new MongoDB\BSON\UTCDateTime(strtotime('-1 year') * 1000)
]
]);
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
Here is the explanation for the above code:
- The
deleteManymethod deletes all documents matching the query. - The query uses the
$ltoperator to find documents wherelast_activeis earlier than one year ago.
Deleting documents may not always go smoothly. You need to handle potential errors. For instance, there could be connection issues or invalid queries. Here is how you can handle errors:
try {
$deleteResult = $collection->deleteOne([
'email' => 'nonexistent@example.com'
]);
if ($deleteResult->getDeletedCount() === 0) {
echo "No documents matched the criteria.";
} else {
echo "Deleted " . $deleteResult->getDeletedCount() . " document(s).";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
This ensures that your script does not crash and provides feedback when no documents match the deletion criteria.
Let’s summarize it.
Wrapping Up
Here are the main points covered in this article about deleting documents in MongoDB using PHP:
- Deleting a Single Document:You can use the
deleteOnemethod to remove the first document that matches a given condition, such as deleting a user with a specific email address. - Deleting Multiple Documents:The
deleteManymethod allows you to remove all documents that match a query. This is useful for tasks like cleaning up records based on time or other criteria. - Error Handling:Always handle potential errors, such as connection issues or invalid queries, to ensure your application runs smoothly and provides helpful feedback to users.
Similar Reads
PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…
You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…
A PHP float is a kind of number that has a decimal point, like 2.45 or 0.11. It’s also called…
The mb_strtolower() function in PHP turns every letter in a string into lowercase. It works with multibyte encodings like UTF-8.…
The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…
PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…
The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…
Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category…
Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…
User input can be unpredictable and dangerous. A simple form submission might carry malicious code or invalid data and lead…