How to delete data from MongoDB using PHP?

by tressie.damore , in category: PHP Databases , 2 years ago

How to delete data from MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 2 years ago

@tressie.damore 

To delete data from MongoDB using PHP, you can use the deleteOne() or deleteMany() methods of the MongoDB PHP Library.


Here's an example code snippet that shows how to delete a single document from a collection in MongoDB using PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
//connect to MongoDB server
$mongoClient = new MongoDBClient("mongodb://localhost:27017");

//select database and collection
$database = $mongoClient->mydatabase;
$collection = $database->mycollection;

//delete a single document from the collection
$deleteResult = $collection->deleteOne(['_id' => new MongoDBBSONObjectID('document_id_here')]);

//check if the document was successfully deleted
if ($deleteResult->getDeletedCount() === 1) {
    echo "Document deleted successfully";
} else {
    echo "Document not found or not deleted";
}
?>


In the above example, the deleteOne() method is used to delete a single document from the mycollection collection in the mydatabase database. The '_id' field is used to identify the document to be deleted, and the new MongoDBBSONObjectID('document_id_here') creates a new MongoDB ObjectID instance with the value of the document's _id field.


Similarly, to delete multiple documents from a collection, you can use the deleteMany() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
//connect to MongoDB server
$mongoClient = new MongoDBClient("mongodb://localhost:27017");

//select database and collection
$database = $mongoClient->mydatabase;
$collection = $database->mycollection;

//delete all documents with age greater than 30
$deleteResult = $collection->deleteMany(['age' => ['$gt' => 30]]);

//check if the documents were successfully deleted
if ($deleteResult->getDeletedCount() > 0) {
    echo "Documents deleted successfully";
} else {
    echo "No documents found or not deleted";
}
?>


In the above example, the deleteMany() method is used to delete all documents from the mycollection collection in the mydatabase database where the age field is greater than 30. The $gt operator is used to specify the condition for the age field. The getDeletedCount() method is used to check the number of documents deleted.