How to Delete Documents in MongoDB with PHP

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 deleteOne method is used to delete the first document matching the query.
  • The query specifies the criteria for deletion (email => 'user@example.com').
  • The getDeletedCount method 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 deleteMany method deletes all documents matching the query.
  • The query uses the $lt operator to find documents where last_active is 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:

  1. Deleting a Single Document:You can use the deleteOne method to remove the first document that matches a given condition, such as deleting a user with a specific email address.
  2. Deleting Multiple Documents:The deleteMany method 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.
  3. 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

Polymorphism in PHP: How It Works with Examples

PHP 5 added support for classes and interfaces. This made object-oriented code possible with one feature being polymorphism. That means…

PHP Strings: Types, Variables & Syntax Tips

If you start working with PHP, it won't take you that long to figure out that strings are everywhere. Besides…

filter_has_var Function: Check if Input Exists in PHP

User input does not always come through as expected. Sometimes values are missing or not set at all. This can…

PHP Singleton Pattern: How to Use with Examples

The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

PHP fclose(): Close Access of File Manipulation

Actually, PHP has a built-in function that doesn’t get the spotlight—fclose(). It ends the file manipulation code. Let’s break down…

Class and Object in PHP: How They Work with a Real Example

Classes and objects are important parts of OOP in PHP. They help you organize your code so you can update…

PHP Filters: How to Validate and Sanitize User Inputs

User input can be unpredictable and dangerous. A simple form submission might carry malicious code or invalid data and lead…

Install PHP on Operating System: Ubuntu, Windows, and macOS

In this tutorial, you will learn how to install PHP on your Operating system such as Ubuntu, Windows, or macOS.…

PHP Math: Essential Functions with Examples

PHP math may sound like a pretty simple thing, but I assure you it's a set of tools that will…

PHP $_REQUEST: Learn How to Capture User Inputs

Today, we will discuss the most prominent and useful superglobal in PHP, $_REQUEST, to get user input. The $_REQUEST array lets you retrieve…

Previous Article

How to Update Documents in MongoDB Using PHP

Next Article

PHP List MongoDB Collections

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.