Jump to content

why i can't use the "administration command" in php when i am working in mongoDB


Recommended Posts

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::listDatabases()

this error keep showing when i wanted to use the administration command for mongodb using php. I do not know whats the problem here and someone with kind soul please help me. The following codes is what i have tried which cause that error.

 

<?php
$client =  new MongoDB\Driver\Manager(  'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/test'
 );
try{ 
    $dbs = $client->listDatabases(); 
    echo '<pre>';
    print_r($dbs);
    echo '</pre>';
    // Or Nothing if you just wanna check for errors 
}
catch(Exception $e){
    echo "Unable to connect to Database at the moment ! ";
    exit();
}

$colecciones = $client->listCollections();
foreach ($colecciones as $col) {
    echo $col->getName();
}

?>

what i am trying to do here is to make sure that my database connection is successful and also list out the collection name of my mongodb database.

Link to comment
Share on other sites

  • 6 months later...

Well, there are some logical error with your code, you can try below code to do this.

<?php
require 'vendor/autoload.php'; // Make sure to include the MongoDB PHP library autoload file

$client = new MongoDB\Client('mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'@'.$_ENV['ATLAS_CLUSTER_SRV'].'/test');

try {
    $databases = $client->listDatabases();
    foreach ($databases as $databaseInfo) {
        echo "Database: " . $databaseInfo['name'] . "\n";
    }
} catch (Exception $e) {
    echo "Unable to connect to the database at the moment!";
    exit();
}

$database = $client->selectDatabase('your_database_name'); // Replace with your actual database name
$collectionNames = $database->listCollectionNames();
foreach ($collectionNames as $collectionName) {
    echo "Collection: " . $collectionName . "\n";
}
?>

Thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.