How to drop a collection in MongoDB using PHP?

by muriel.schmidt , in category: PHP Databases , 2 years ago

How to drop a collection in MongoDB using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 2 years ago

@muriel.schmidt 

To drop a collection in MongoDB using PHP, you can use the drop() method of the MongoCollection class. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php
// connect to MongoDB server
$mongo = new MongoClient();

// select database and collection
$db = $mongo->selectDB('mydb');
$collection = $db->selectCollection('mycollection');

// drop the collection
$collection->drop();

// close connection
$mongo->close();
?>


In this example, we first create a new MongoClient object to connect to the MongoDB server. We then select the database and collection we want to work with using the selectDB() and selectCollection() methods of the MongoClient object.


To drop the collection, we simply call the drop() method on the MongoCollection object.


Finally, we close the connection to the MongoDB server using the close() method of the MongoClient object.